Top ten sorting algorithms (JavaScript language)

One: Bubble sort

Motion picture understanding

Insert picture description here

Code
function bubbleSort(arr){
    
    
    for(let i=0;i<arr.length-1;i++){
    
    
        let didSwap = false;
        for(let j=0;j<arr.length-i-1;j++){
    
    
        	// 交换的是相邻索引处元素,所以稳定
            if(arr[j]>arr[j+1]){
    
    
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                didSwap = true;
            }
        }
        if(!didSwap){
    
    
            break;
        }
    }
}
Analysis of Algorithms
  • Average time complexity [time]: O(n 2 )
  • The best case [time]: O(n), which occurs when the array itself is ordered.
  • Worst case [time]: O(n 2 ), which occurs in the reverse order of the array itself.
  • Space complexity [Space]: O(1), only exchange elements in the original array space.
  • Sorting method [Space]: inner sorting
  • Stability [Space]: Stable

Two: select sort

Motion picture understanding

Insert picture description here

Code
function selectSort(arr){
    
    
    for(let i=0;i<arr.length-1;i++){
    
    
        for(let j=i+1;j<arr.length;j++){
    
    
        	// 交换的不是相邻索引处的元素,所以不稳定
            if(arr[i]>arr[j]){
    
    
                let temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}
Analysis of Algorithms
  • Average time complexity [time]: O(n 2 )
  • Best case [time]: O(n 2 )
  • Worst case [time]: O(n 2 )
  • Space complexity [space]: O(1), only exchange elements in the original array space.
  • Sorting method [Space]: inner sorting
  • Stability [Space]: Unstable (such as [5 a ,8,5 b ,2,9], after the first round of selection and exchange, it is [2,8,5 b ,5 a ,9], two 5s are in order Changed).

Three: Insertion sort

Motion picture understanding

Insert picture description here

Code
function insertSort(arr){
    
    
    for(let i=1;i<arr.length;i++){
    
    
        let insert_index = i;
        let insert_ele = arr[i];
        // 找到插入位置
        for(let j=i-1;j>=0;j--){
    
    
            if(insert_ele<arr[j]){
    
    
                insert_index = j;
            }else{
    
    
            	break;
			}
        }
        // 腾出插入位置
        for(let z=i-1;z>=insert_index;z--){
    
    
        	// 交换的是相邻索引处元素,所以稳定
            arr[z+1] = arr[z];
        }
        // 插入元素
        arr[insert_index] = insert_ele;
    }
}
Analysis of Algorithms
  • Average time complexity [time]: O(n 2 )
  • The best case [time]: O(n), which occurs when the array itself is ordered, and each element (except the first element) is inserted once more than once.
  • Worst case [time]: O(n 2 ), which occurs when the array itself is disordered.
  • Space complexity [space]: O(1), only exchange elements in the original array space.
  • Sorting method [Space]: inner sorting
  • Stability [Space]: Stable

Four: Hill sort

Motion picture understanding

Insert picture description here

Code
function shellSort(arr){
    
    
    let gap = Math.floor(arr.length/2);
    while(gap>=1){
    
    
        for(let i=gap;i<arr.length;i++){
    
    
            shellSortHelp(arr,i,gap);
        }
        gap = Math.floor(gap/2);
    }
}
// 在当前增量为gap的分组情况下,把索引为i的元素插入至正确位置。
function shellSortHelp(arr,i,gap){
    
    
    let insert_index = i;
    let insert_ele = arr[i];
    // 找到插入位置(间隔为gap)
    for(let j=i-gap;j>=0;j=j-gap){
    
    
    	// 交换的不是相邻索引处的元素,所以不稳定
        if(insert_ele<arr[j]){
    
    
            insert_index = j;
        }else{
    
    
			break
		}
    }
    // 腾出插入位置
    for(let z=i-gap;z>=insert_index;z=z-gap){
    
    
        arr[z+gap] = arr[z];
    }
    arr[insert_index] = insert_ele;
}
Analysis of Algorithms
  • Average time complexity [time]: O(nlog2 n)
  • Best case [time]: O(nlog2 n)
  • Worst case [time]: O(nlog2 n)
  • Space complexity [space]: O(1), only exchange elements in the original array space.
  • Sorting method [Space]: inner sorting
  • Stability [Space]: Unstable (such as [5 a , 5 b , 2, 9], after the first packet exchange is [2 , 5 b , 5 a , 9], the second packet sequence remains unchanged, two The order of 5 changed)

Five: merge sort

Motion picture understanding

Insert picture description here

Code
function mergeSort(arr,left,right) {
    
    
    if(left<right){
    
    
        // 1.分治分组时,索引中值二分
        let center = Math.floor((left+right)/2)
        // 左分
        mergeSort(arr,left,center)
        // 右分
        mergeSort(arr,center+1,right)
        // 左右合一
        mergeSortHelp(arr,left,right,center)
    }
}
function mergeSortHelp(arr,left,right,center) {
    
    
    let pointer_left = left
    let pointer_right = center+1
    let arr_copy = arr.slice()// 借用到拷贝数组,空间复杂度O(n)
    for(let i=left;i<=right;i++){
    
    
        if(pointer_left===center+1){
    
    
            for(let j=i;j<=right;j++){
    
    
                arr[j] = arr_copy[pointer_right++]
            }
            break
        }
        else if(pointer_right===right+1){
    
    
            for(let j=i;j<=right;j++){
    
    
                arr[j] = arr_copy[pointer_left++]
            }
            break
        }
        // 2.合并比较时,先判断取左边数组元素,结合1判断 归并排序稳定
        else if(arr_copy[pointer_left]<=arr_copy[pointer_right]){
    
    
            arr[i] = arr_copy[pointer_left++]
        }
        else{
    
    
            arr[i] = arr_copy[pointer_right++]
        }
    }
}
Analysis of Algorithms
  • Average time complexity [time]: O(nlogn)
  • Best case [time]: O(nlogn)
  • Worst case [time]: O(nlogn)
  • Space complexity [Space]: O(n), copy array will be used.
  • Sorting method [space]: outer sorting
  • Stability [Space]: Stable.

Six: Quick sort

Motion picture understanding

Insert picture description here

Code
// 分治法
function quickSort(arr,left,right){
    
    
    if(left<right){
    
    
        let loginMid = arrAdjust(arr,left,right);
        quickSort(arr,left,loginMid-1);
        quickSort(arr,loginMid+1,right);
    }
}
// 挖坑填数(比较时使用双指针索引值比对交换,所以不稳定)
function arrAdjust(arr,left,right){
    
    
    let pointerLeft = left;
    let pointerRight = right;
    let referNum = arr[pointerLeft];
    while (pointerLeft<pointerRight){
    
    
        //arr[pointerLeft]为坑位
        while(pointerLeft<pointerRight && arr[pointerRight]>referNum){
    
    
            pointerRight--;
        }
        if(pointerLeft<pointerRight){
    
    
            arr[pointerLeft] = arr[pointerRight];
        }
        //arr[pointerRight]为坑位
        while(pointerLeft<pointerRight && arr[pointerLeft]<referNum){
    
    
            pointerLeft++;
        }
        if(pointerLeft<pointerRight){
    
    
            arr[pointerRight] = arr[pointerLeft];
        }
    }
    //pointerLeft==pointerRight,使用基准数占住坑位
    arr[pointerLeft] = referNum;
    // 返回逻辑中间值索引,此时arr[x]<arr[pointerLeft]<arr[y]。(x<pointerLeft<y)
    return pointerLeft;
}
Analysis of Algorithms
  • Average time complexity [time]: O(nlogn)
  • Best case [time]: O(nlogn)
  • Worst case [time]: O(n 2 )
  • Space complexity [space]: O(nlogn)
  • Sorting method [Space]: inner sorting
  • Stability [Space]: Unstable (the median value of index logic is divided into two)

Seven: Heap sort

Motion picture understanding

Insert picture description here

Code
// 1.堆排序
let len = 0// heapSort和heapAdjust方法共享。
function heapSort(arr){
    
    
    buildMaxHelp(arr)
    for(let i=arr.length-1;i>0;i--){
    
    
        swap(arr,0,i)
        len--
        heapAdjust(arr,0)
    }
}
// 2.构建大顶堆
function buildMaxHelp(arr){
    
    
    len = arr.length
    // 堆数组:索引为[0,Math.floor(arr.length)-1]的为非叶子结点。
    for(let i=Math.floor(arr.length/2)-1;i>=0;i--){
    
    
        heapAdjust(arr,i)
    }
}
// 3.堆调整:调整为以arr[i]为堆顶的堆为大顶堆
function heapAdjust(arr,i){
    
    
    let left = 2*i+1
    let right = 2*i+2
    let largest = i// 最大元素的索引指针
    if(right<len && arr[right]>arr[largest]){
    
     // 排序已提出的元素不参与构建堆,此处len不能为arr.length
        largest = right
    }
    if(left<len && arr[left]>arr[largest]){
    
    
        largest = left
    }
    if(largest!=i){
    
    
        swap(arr,i,largest)
        heapAdjust(arr,largest)// 堆变化后,递归调整子堆
    }
}
// 4.元素交换
function swap(arr,i,j){
    
    
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
  • Tencent written test questions: unordered and non-repeated numbers, take out the K-th largest number (take out the k-th smallest number with a small top pile).
function heapsort2(arr,k){
    
    
    buildMaxHeap(arr)
    
    for(let i=arr.length-1;i>=arr.length-k;i--){
    
    // 只需遍历到arr.length-k即可
        swap(arr,0,i)
        len--
        heapify(arr,0)
    }
    return arr[arr.length-k]
}
Analysis of Algorithms
  • Average time complexity [time]: O(nlogn)
  • Best case [time]: O(nlogn)
  • Worst case [time]: O(nlogn)
  • Space complexity [space]: O(1)
  • Sorting method [Space]: inner sorting
  • Stability [Stability]: Unstable

Eight: counting and sorting

Motion picture understanding

Insert picture description here

Code
function countingSort(arr,max = Math.max(...arr)){
    
    
    let bucketArr = new Array(max+1)
    // 装篮
    for(let i=0;i<arr.length;i++){
    
    
        if(!bucketArr[arr[i]]){
    
    
            bucketArr[arr[i]] = 0
        }
        bucketArr[arr[i]]+=1
    }

    // 出篮
    let pointer = 0
    for(let j=0;j<bucketArr.length;j++){
    
    
        while (bucketArr[j]-->0){
    
    
            arr[pointer++]=j
        }
    }
}
Analysis of Algorithms
  • Average time complexity [time]: O(n+k). (N=arr.length,k=bucket.length)
  • Best case [time]: O(n+k)
  • Worst case [time]: O(n+k)
  • Space complexity [space]: O(k)
  • Sorting method [space]: outer sorting
  • Stability [Space]: Stable (counting sorting is not based on element comparison, and stability here does not refer to the above unoptimized counting sorting code).

Nine: Bucket sorting

Ten: base sort

Guess you like

Origin blog.csdn.net/jw2268136570/article/details/104779778