排序算法汇总

选择排序

  1. 简单选择排序

复杂的插入排序
时间. O(n2)
空间 O(1)

function sort(arr) {
    for (i = 0; i < arr.length-1;i++) { 
        for (j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) {
                let tp = arr[i]
                arr[i] = arr[j]
                arr[j] = tp
            }
         }
    }
 }

let arr = [2, 1, 3, 8, 4, 6]

sort(arr)

console.log(arr)
  1. 堆排序

复杂的插入排序
时间. O(nlog2n)
空间 O(1)

function heapAdjust(arr, parentIdx, length) { 

    let childIdx = parentIdx * 2 + 1

    while (childIdx=0 ;i--) { 
        heapAdjust(arr,i,arr.length)
    }
}

function heapSort(arr) {

    for (let i = arr.length - 1; i >= 0; i--){
        //把最小的交换到数组最后
        let tp = arr[i]
        arr[i] = arr[0]
        arr[0] = tp
        heapAdjust(arr,0,i)
    }
    console.log(arr)
}

let arr = [2, 1, 3, 8, 4, 6]

buildHeap(arr)
heapSort(arr)
 
 

插入排序

  1. 简单插入排序

function insertSort(arr) {
    for (i =0; i= 0; j--){
            if (arr[j] < arr[j - 1]) {
                let tp = arr[j]
                arr[j] = arr[j - 1]
                arr[j-1]=tp
             }
        }
    }
    return arr
}


let arr = [2, 1, 3, 8, 4, 6]

let re = insertSort(arr)

console.log(re)```


  1. 希尔排序

复杂的插入排序
时间 O(n2)
空间 O(1)

function insertSort(arr) {

    for (let d = Math.floor(arr.length / 2); d >= 1; d=Math.floor(d / 2)) {

         for (let i = 0; i < d; i++){
            for (let j = i;ji ;k-=d) {
                    if (arr[k] < arr[k - d]) {
                        let tp = arr[k]
                        arr[k] = arr[k - d]
                        arr[k-d]=tp
                    }
                }
            }
        }
    }
    return arr
}


let arr = [2, 1, 3, 8, 4, 6]

let re = insertSort(arr)

console.log(re)

归并排序

  1. 二路归并

function sort(left, right) {
    let r = []
    while (left.length && right.length) {
        if (left[0] < right[0]) {
            r.push(left.shift())
        } else {
            r.push(right.shift())
        }
    }
    r.push(...left,...right)
    return r
}
function mergeSort(arr) {
    if (arr.length > 1) {
        let mid = Math.floor(arr.length / 2)
        let left = arr.slice(0, mid)
        let right = arr.slice(mid)
        return sort(mergeSort(left),mergeSort(right))
    }
    return arr
}

let arr = [2, 1, 3, 8, 4, 6]

console.log(mergeSort(arr)) 

 

你可能感兴趣的:(js,排序算法,javascript,算法)