js快速排序

旧时模样 提交于 2020-01-14 10:51:16

/**
*

  • 快速排序
  • 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 }),
    );
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!