Quick sort (JS Implementation)

Time:2022-7-28

thought

The basic idea of quick sort is to select an element in the array as a keyword, and divide the array to be sorted into two parts through one sort. The left part is smaller than all keywords, and the right part is larger than all keywords. Then repeat the operation on the left and right data respectively until all the elements are in order, and you get a completely ordered array.

For an example, take the array [4, 5, 2, 7, 3, 1, 6, 8] as an example. We select the leftmost element of the array as the keyword pivot

快速排序quickSort图示流程

The first step starts from the right, moves the right pointer to the left, meets 8, 6, are larger than 4, until meets 1, is smaller than 4, therefore moves 1 to the leftmost. The right pointer stays still and starts moving the left pointer.

快速排序quickSort图示流程

Move the left pointer and find that 5 is larger than the keyword pivot 4, so moving 5 to the position of the right pointer just recorded is equivalent to moving all values larger than pivot to the right. Then start moving the right pointer.

快速排序quickSort图示流程

Move the right pointer and find that 3 is smaller than pivot, so move 3 to the position just recorded by the left pointer and start moving the left pointer.

快速排序quickSort图示流程

Move the left pointer, 2 is smaller than pivot, and then move it. It is found that 7 is larger than pivot, so put 7 in the position recorded by the right pointer, and start moving the right pointer again.

快速排序quickSort图示流程

Move the right pointer and find that the two pointers overlap. Insert the value of pivot into the pointer position (equivalent to finding the exact position of pivot after sorting). This sorting is over.

快速排序quickSort图示流程,动态图

After a sorting, record the overlapping pointer positions, and continue the above operations on the left and right sub arrays respectively until they are divided into single element arrays. After all operations are completed, the entire array becomes an ordered array.

The dynamic graph is shown below. The dynamic graph uses an unordered array of 20 elements to demonstrate. The gray background is the sub array currently being sorted, and the orange is the current pivot. For the convenience of demonstration, the pointer position is reflected by exchanging elements.
image

JS implementation

The code is as follows:

const quickSort = (array)=>{
  quick(array, 0, array.length - 1)
}

const quick = (array, left, right)=>{
  if(left < right){
    let index = getIndex(array, left, right);
    quick(array, left, index-1)
    quick(array, index+1, right)
  }
}

const getIndex = (array, leftPoint, rightPoint)=>{
  let pivot = array[leftPoint];
  while(leftPoint < rightPoint){
    while(leftPoint < rightPoint && array[rightPoint] >= pivot) {
      rightPoint--;
    }
    array[leftPoint] = array[rightPoint]
    //Swap (array, leftpoint, rightpoint) // using swap, the effect is exactly the same as that of dynamic graph presentation
    while(leftPoint < rightPoint && array[leftPoint] <= pivot) {
      leftPoint++;
    }
    array[rightPoint] = array[leftPoint]
    // swap(array, leftPoint, rightPoint)
  }
  array[leftPoint] = pivot
  return leftPoint;
}

const swap = (array, index1, index2)=>{
  var aux = array[index1];
  array.splice(index1, 1, array[index2])
  array.splice(index2, 1, aux)
}

const createNonSortedArray = (size)=>{
  var array = new Array();
  for (var i = size; i > 0; i--) {
    //array.push(parseInt(Math.random()*100));
    array.push(i*(100/size));
    array.sort(function() {
      return (0.5-Math.random());
    });
  }
  return array;
}

var arr = createNonSortedArray(20);
quickSort(arr)
console.log(arr)	//[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

Time complexity

Fast sorting obviously uses the idea of divide and conquer. The key is to choose the pivot. If the data can be divided into two halves every time, the depth of the recursive tree is logn, and the time complexity of fast sorting is O (nlogn).
If each pivot divides the array into a part empty and a part for all data, then the depth of the recursive tree is n-1, so the time complexity becomes o (n^2).

According to the above time complexity analysis, we find that if a data is completely ordered, then using our quick sort algorithm above is the worst case, so how to choose pivot has become the focus of optimizing quick sort. If we continue to use the above algorithm, then we can randomly choose pivot to replace the first element of the array as the pivot.

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]