For an input array containing n numbers,Quick sortingIs the worst case where the time complexity isO (n2). Although the time complexity in the worst case is very poor, fast sorting is usually the best choice in actual sorting applications, because its average performance is very good: its expected time complexity isO (nlgn)In addition, the constant factor hidden in O (nlgn) is very small. In addition, it can sort the original address and even work well in the virtual storage environment.
Used for quick sortingSub-GovernanceIdea:
Decomposition: Convert the ArrayA [low... high]Divided into two subarraysA [low .. mid-1]AndA [mid + 1 .. high],MakeA [low .. mid-1]The element in the sub-array is smaller than A [mid ],A [mid + 1 .. high]If all elements are greater than the [mid] element, the mid position is returned;
Solution: Uses recursive calling to quickly sort sub-arrays;
Merge: Because the sub-array is sorted by the original address, it does not need to be merged: The array is already ordered.
WhereDecomposition:
ProceedOriginal address Rearrangement:
For exampleA [] = {2, 8, 7, 1, 3, 5, 6, 4}For quick sorting;
Perform original address rearrangement in Partition:
Take the last elementX = 4,Light grayPart is <= x,Dark grayThe part is> x; The first round of sorting ends here;
Continue runningQuickSortUntil p> = r (that is, low> = high );
Code:
# Include
# Include
# Include
Using namespace std; void swap (int & m, int & n) // exchange {int temp = m; m = n; n = temp;} int Partition (int *, int low, int high) {int I = low-1; int low = A [high]; // The last element serves as the base point for (int j = low; j