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
- Select a value in an array as the standard.
- 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.
- Recurse the above process until it cannot be decomposed
Algorithm process
- We define a quick sort method QuickSort, we also need to pass in the start and end of the sort so that each recursion
- 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 figure
r
- Define two pointers
i
andj
- j, traversing the pointer, the pointer value and the standard value of the current is
r
compared - 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
i
pointer 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