Quick Sort
In the array to be sorted, the first arbitrary selection of data as the key data (usually take the first or the middle one), and then all the smaller than its number is placed on its left, all the larger than its number is placed on its right, this process is called a fast sort of a trip. Recursively until the sorting is finished.
Starting from J forward Search (j--), encounter less than Key will be array[j] and Array[i] exchange, from I backward Search (i++), encounter greater than Key will array[i] and array[j] exchange;
Fast sorting is an unstable sorting algorithm, which means that the relative position of multiple identical values may change at the end of the algorithm.
Give me a chestnut:
Key=6 the first number as a key data;
6 2 7 3 8 9 at this time i=0;j=5;
3 2 7 6 8 9 at this time i=0;j=3;
3 2 67 8 9 at this time i=2;j=3;
3 2 6 7 8 9 at this time i=j=2; the first cycle ends
functionQuickSort (array) {functionsort (prev, numsize) {vari =prev; varj = numsize-1; varKey =Array[prev]; if((Numsize-prev) > 1) { while(I <j) { for(; i < J; j--){ if(Array[j] <key) {Array[i+ +] = Array[j];//A[i] = a[j]; i + = 1; Break; }; } for(; i < J; i++){ if(Array[i] >key) {Array[j--] =Array[i]; Break; }}} Array[i]=key; Sort (0, i); Sort (i+ 1, numsize); }} sort (0, Array.Length); returnArray;}
There is also an easy-to-understand approach:
Set two empty arrays left and right, traverse the entire array, and push in to leave if it encounters less critical data, otherwise put it in. This is a better understanding of the intermediate numbers as key data.
functionQuickSort (arr) {if(Arr.length <= 1){ returnarr; } varPivotindex = Math.floor (ARR.LENGTH/2); Take the middle as the benchmarkvarPivot = Arr.splice (pivotindex, 1) [0];//take the datum out and delete it from the original array varleft = []; varright = []; for(vari = 0;i < arr.length;i++){ if(Arr[i] <pivot) {Left.push (arr[i]); }Else{Right.push (arr[i]); } } returnQuickSort (left). Concat ([Pivot],quicksort (right));}
Data structures and algorithms-Quick sorting