/**
*
- 快速排序
- arr:[]排序的数组
type:true 小到大 false大到小
filed:如过比的是对象里面的谋个值,则传字段
*/
export function listSort(obj: any): Array {
const { arr, type = true, filed = false } = obj;
const len = arr.length;
if (len <= 1) {
return arr;
}
const pivotInedex = Math.floor(len / 2);
const pivot = arr.splice(pivotInedex, 1)[0];
let left = [];
let right = [];
for (let i = 0; i < arr.length; i++) {
const obj = arr[i];
let bool = true;
if (type) {
bool = filed ? obj[filed] < pivot[filed] : obj < pivot;
} else {
bool = filed ? obj[filed] > pivot[filed] : obj > pivot;
}
if (bool) {
left.push(obj);
} else {
right.push(obj);
}
}
return listSort({ arr: left, filed: filed, type: type }).concat(
[pivot],
listSort({ arr: right, filed: filed, type: type }),
);
}
本文深入解析了一种高效的排序算法——快速排序。通过递归方式,选取基准元素将数组分为两部分,一部分的所有元素都比另一部分小,然后分别对这两部分进行排序。支持自定义比较类型,包括对象内部字段的比较。
2142

被折叠的 条评论
为什么被折叠?



