Basic ideas
Quick Sort (Quicksort) is an improvement on the bubbling sort, also known as the split-exchange sort (partition-exchange sort.
Quick sort uses the Divide and conquer strategy to divide a sequence (list) into two sub-sequences (sub-lists).
The steps are:
①. Pick an element from the sequence called "Datum" (pivot)
②. Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, and all elements are larger than the base value behind the datum (the same number can be on either side). At the end of this partition, the datum is in the middle of the sequence. This is called partition (partition) operation.
③. recursively (recursive) sorts sub-columns that are less than the base value element and that are larger than the base value element
The process of sorting a column of numbers using the Quick Sort method
sorting efficiency
On average, sort n items to 0 (n log n) comparisons. In the worst case scenario, a 0 (N2) comparison is required, but this is not a common situation. In fact, fast sequencing is usually much faster than the other 0 (n log n) algorithms because its internal loop (inner Loop) can be implemented efficiently on most architectures.
Worst time complexity 0 (n^2)
Optimal time complexity 0 (n log n)
Average Time complexity 0 (n log n)
The worst spatial complexity varies depending on how it is implemented
Java implementation
Public Static voidMain (string[] args) {int[] arr = {8,1,0,4,6,2,7,9,5,3}; QuickSort (arr,0, arr.length-1); for(intI:arr) {System.out.println (i); } } Public Static voidQuickSort (int[]arr,intLowintHigh) {if(Low < High) {intMiddle = getmiddle (arr, low, high); QuickSort (arr, low, middle-1); QuickSort (arr, Middle +1, high); } } Public Static intGetmiddle (int[]List,intLowintHigh) {intTMP =List[Low]; while(Low < High) { while(Low < High &&List[High] >= tmp) {high--; }List[Low] =List[High]; while(Low < High &&List[Low] <= tmp) {low++; }List[High] =List[Low]; }List[Low] = TMP;returnLow }
Operation Result:
Analysis:
8 is the median, the red arrow indicates low, and the green arrow indicates high
The ① scans forward from high to the first value smaller than 8 with a 8 interchange.
The ② scans backward from low to a value of 8 with 8 switching.
③ repeats the ①② process only to, High=low completes a quick sort, and then recursion the subsequence.
[Data structure] quick sort