"Introduction to Algorithms" @书Note@ Chapter 7-Quick Sort (including js version code implementation)

Introduction to Quick Sort

Quick sort is a sorting method with a worst-case time complexity of n^2. Although the complexity is poor in the worst case, quick sort is usually a better choice in practical application sorting. Because its average performance is very good nLgn.

Algorithm ideas

  1. Select a value in an array as the standard.
  2. Put the values ​​less than the standard to the left of the array, and put the values ​​greater than the standard to the right of the array.
  3. Recurse the above process until it cannot be decomposed

Algorithm process

  1. We define a quick sort method QuickSort, we also need to pass in the start and end of the sort so that each recursion
  2. We need a method to perform the steps 1 and 2 in the above idea and finally return an intermediate coordinate to distinguish the left and right positions of the array
  • Define this method as partition, and its implementation process is like this
  • Take the last digit as its reference value, which is the figurer
  • Define two pointers iandj
  • j, traversing the pointer, the pointer value and the standard value of the current is rcompared
  • If the value of the j pointer is greater than r, continue to traverse. If the value of the j pointer is less than or equal to r, then the i pointer takes a step forward and the values ​​of the positions of the i and j pointers swap positions
  • From the above process, we can understand that the ipointer is the boundary of the two arrays
  • When the j pointer is traversed, insert r after i to complete the entire partition process

Algorithm implementation

Here quick sort is the in-situ sort implemented

function exchange(arr, a, b) {
    
    
    let tem = arr[a]
    arr[a] = arr[b]
    arr[b] = tem
}
function partition(input, l, r) {
    
    
    let s = input[r]
    let i = l - 1
    for (let j = l; j < r; j++) {
    
    
        if (input[j] <= s) {
    
    
            ++i
            exchange(input, i, j)
        }
    }
    exchange(input, i + 1, r)
    return i + 1
}
function QuickSort(arr, l, r) {
    
    
    if (l < r) {
    
    
        let mid = partition(arr, l, r)
        QuickSort(arr, l, mid - 1)
        QuickSort(arr, mid + 1, r)
    }
}
module.exports = QuickSort

Guess you like

Origin blog.csdn.net/weixin_38616850/article/details/110839112