JS排序算法

quickSort = (arr, left, right) => {
    if (!arr) return null
    let start = left || 0
    let end = right || arr.length
    if (start < end) {
        let num = getNum(arr, start, end)
        quickSort(arr, start, num - 1)
        quickSort(arr, num + 1, end)
    }
    return arr
}

getNum = (arr, start, end) => {
    let pivot = start,                      // 设定基准值(pivot)
        index = pivot + 1;
    for (let i = index; i < end; i++) {
        if (arr[i] < arr[pivot]) {
            [arr[i], arr[index]] = [arr[index], arr[i]]
            index++
        }
    }
    index--
    [arr[pivot], arr[index]] = [arr[index], arr[pivot]]
    return index

}


mergeSort = (arr) => {
    if (arr.length < 2) return arr
    let mid = Math.floor(arr.length / 2)
    let left = arr.slice(0, mid)
    let right = arr.slice(mid, arr.length)
    return merge(mergeSort(left), mergeSort(right))
}

merge = (left, right) => {
    let result = []
    while (left.length && right.length) {
        if (left[0] < right[0]) result.push(left.shift())
        else result.push(right.shift())
    }
    // while (left.length) {
    //     result.push(left.shift())
    // }
    if(left.length) result=result.concat(left.reverse())
    if(right.length) result=result.concat(right.reverse())
    // while (right.length) {
    //     result.push(right.shift())
    // }

    return result
}



bubbleSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        for (let j = i; j < arr.length; j++) {
            if (arr[i] > arr[j]) [arr[i], arr[j]] = [arr[j], arr[i]]
        }
    }
    return arr
}



choseSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        let key = i
        for (let j = i; j < arr.length; j++) {
            if (arr[key] > arr[j]) key = j
        }
        [arr[i], arr[key]] = [arr[key], arr[i]]
    }
    return arr
}


insertionSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        let key = arr[i]
        for (var j = i-1; j >=0 &&arr[j]>key; j--) {
            arr[j+1] = arr[j]
        }
        arr[j+1] = key
    }
    return arr
}

shellsSort=(arr)=>{
    let gap = Math.floor(arr.length/3)
    while (gap>0){
        for (let i = gap;i<arr.length;i++){
            let key = arr[i]
            for (var j = i-gap;j>=0&&arr[j]>key;j-=gap){
                arr[j+gap] = arr[j]
            }
            arr[j+gap] = key
        }
        gap = Math.floor(gap/3)
    }
    return arr
}


let arr = [4, 5, 6, 3, 2, 1, 9, 8, 7]
// console.log(quickSort(arr))
console.log(shellsSort(arr));
a.addEventListener()

你可能感兴趣的:(算法)