js 數組快速排序函數封裝

/**
*

  • 快速排序
  • 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 }),
    );
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章