Sorting Algorithm
This article explains the ideas and coding of three sorting algorithms: bubble sort, quick sort, and merge sort
Bubble Sort
Idea: Compare two adjacent numbers in turn, putting the smaller number in the front and the larger number in the back.
Until one run is completed, at this time, the largest number is placed in the last position, where it should be after sorting. By analogy, bubble the second largest number to the penultimate position, run i times, put all i numbers in its designated position, and the sorting is complete.
function bubbleSort(arr) {
const len = arr.length;
for (let i = 0; i < len; i++) {
// 每次把最大值冒泡到最后
for (let j = 1; j < len - i; j++) {
if (arr[j - 1] > arr[j]) {
[arr[j - 1], arr[j]] = [arr[j], arr[j - 1]];
}
}
}
return arr;
}
Quick sort
Idea: Set a boundary value, divide the array into two parts by the boundary value, put the one smaller than it on the left, and put the one larger than it on the right.
After running once, then the dividing value is where it should be (because the left is smaller than it, and the right is larger than it), and the two ends of the split continue to run according to this logic (recursive).
function quickSort(arr) {
const sort = (L, R) => {
if (L >= R) return;
let l = L;
let r = R;
// 选择一个基准值,把小于它的,放在左边,大于它的,放在右边
// 拆分后的两端继续这样做
const pivot = arr[l];
while (l < r) {
while (l < r && arr[r] > pivot) r--;
if (l < r) {
arr[l] = arr[r];
}
while (l < r && arr[l] < pivot) l++;
if (l < r) {
arr[r] = arr[l];
}
}
arr[l] = pivot;
sort(L, r - 1);
sort(r + 1, R);
};
sort(0, arr.length - 1);
return arr;
}
Merge sort
Idea: Split the array into two parts, and split the two sub-arrays recursively. Until it can no longer be divided, the two-by-two merge (merging) is performed at this time, and the merged sub-sequence is ordered, that is, the two ordered sub-sequences are merged. The merged is the final sorted result.
function mergeSort(arr) {
const merge = (sortV1, sortV2) => {
let sortValue = [];
let i = 0,
j = 0;
while (i < sortV1.length && j < sortV2.length) {
if (sortV1[i] > sortV2[j]) {
sortValue.push(sortV2[j]);
j++;
} else {
sortValue.push(sortV1[i]);
i++;
}
}
if (i < sortV1.length) {
sortValue = sortValue.concat(sortV1.slice(i, sortV1.length));
} else if (j < sortV2.length) {
sortValue = sortValue.concat(sortV2.slice(j, sortV2.length));
}
return sortValue;
};
const sort = (arr) => {
if (arr.length === 1) return arr;
let mid = Math.floor(arr.length / 2);
let v1 = arr.slice(0, mid);
let v2 = arr.slice(mid, arr.length);
const sortV1 = sort(v1);
const sortV2 = sort(v2);
return merge(sortV1, sortV2);
};
return sort(arr);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。