1. 快速排序
// 快速排序
let arr =[ { id: 1, score: 10 }, { id: 2, score: 5 }, { id: 3, score: 14 }];
let lessFunc = function(a, b) {
return a.score <= b.score;
};
let kuaisu = function(arr, lessFunc) {
const quickSort = function(arr, low, high) {
let i = low;
let j = high;
let pivot = arr[low];
if (i >= j) {
return;
}
while (i != j) {
while (i < j && lessFunc(pivot, arr[j])) j--;
if (i < j) arr[i] = arr[j];
while (i < j && lessFunc(arr[i], pivot)) i++;
if (i < j) arr[j] = arr[i];
}
arr[i] = pivot;
quickSort(arr, low, i - 1);
quickSort(arr, i + 1, high);
};
quickSort(arr, 0, arr.length - 1);
return arr;
};
2. 冒泡排序
es6
for(let i in array) {
for(let j in array) {
if(array[j]> array[i]) {
/* 交换 */
let tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
es5
for(var i in array) {
for(var j in array) {
if(array[j]> array[i]) {
/* 交换 */
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}