Open OPY-bbt opened 4 years ago
// 归并排序:分组单独排序,然后合并
function mergeSort(arr) {
const len = arr.length;
if (len <= 1) {
return arr;
}
const index = Math.floor(len / 2);
return merge(mergeSort(arr.slice(0, index)), mergeSort(arr.slice(index)));
}
function merge(arr1, arr2) {
let res = [];
let i = 0;
let j = 0;
while(i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
res.push(arr1[i++]);
} else {
res.push(arr2[j++]);
}
}
if (i !== arr1.length) {
res = res.concat(arr1.slice(i));
}
if (j !== arr2.length){
res = res.concat(arr2.slice(j));
}
return res;
}
// console.log(mergeSort(data));
// 快速排序:找一个基准数,左侧放小于其的数,右侧放大于的。直到需要排序的数量缩减为1
function quickSort(arr) {
if (arr.length <= 1) { return arr; }
const pivotIndex = Math.floor(arr.length / 2);
const pivot = arr.splice(pivotIndex, 1)[0];
const left = [];
const right = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat([pivot], quickSort(right));
}
// console.log(quickSort(data));
// 快速排序:元素交换
function quickSort2(arr, p = 0, r = arr.length - 1) {
if (p >= r) return arr;
const q = partition(arr, p, r);
quickSort2(arr, p, q - 1);
quickSort2(arr, q + 1, r);
return arr;
}
function partition(arr, p, r) {
const pivot = arr[r];
let anchor = p;
for (let i = p; i <= r; i++) {
if (arr[i] < pivot) {
[arr[i], arr[anchor]] = [arr[anchor], arr[i]]
anchor++;
}
}
[arr[anchor], arr[r]] = [arr[r], arr[anchor]];
return anchor;
}
console.log(quickSort2(data));