Quick Sort Basic Features
- Complexity of Time: O (N*LGN)
- Worst: O (n^2)
- Spatial complexity: Best case: O (LGN), worst case: O (N), average: O (LGN)
- Not stable.
About the spatial complexity of the quick sort, thank you for the fate of his father classmate correct me. Describe it in detail.
Quick sort the spatial complexity of one recursive is O (1), since each recursion takes up a space to return the median position.
The best case and average recursion depth is O (LGN), and the corresponding spatial complexity is O (LGN)
In the worst case, the recursion depth is O (n) and the spatial complexity is O (n).
Algorithm
QUICKSORT(A, p, r)
if
p < r
then q ← PARTITION(A, p, r)
//关键
QUICKSORT(A, p, q - 1)
QUICKSORT(A, q + 1, r)
PARTITION(A, p, r)
x ← A[r]
i ← p - 1
for
j ← p to r - 1
do
if
A[j] ≤ x
then i ← i + 1
exchange A[i] <-> A[j]
exchange A[i + 1] <-> A[r]
return
i + 1
Example
Array to sort: 7 3 5 9 8 5 1 10 4 6
Source class declarationclassBasesort { Public: Basesort () {}Virtual voidSort () =0;};classQuickSort: PublicBasesort { Public: QuickSort (intArray[],intlen): Basesort () { This->array =Array; This->len =Len; } voidsort ();Private: intPartitionintArray[],intStartintend); voidQuicksortintArray[],intStartintend);Private: int*Array; intLen;};
////related member function implementationvoidQuicksort::sort () {QuickSort (Array,0, len-1);}voidQuicksort::quicksort (intArray[],intStartintend) { if(Start <end) { intMID = This-partition (Array, start, end); if(Start < mid-1) quicksort (Array, start, mid-1 ); if(Mid +1<end) Quicksort (Array, Mid+1, end); }}intQuickSort::p artition (intArray[],intStartintend) { intI, J, X, TMP; X=Array[end]; I= Start-1; for(j = start; J < End; J + + ) { if(Array[j] <=x) {i++; TMP=Array[j]; ARRAY[J]=Array[i]; Array[i]=tmp; }} tmp=Array[end]; Array[end]= array[i+1]; Array[i+1] =tmp; //if (DEBUG) {//PrintArray (Array, Len, "Midresult:"); //} returni+1;}
Test:intMainintargcChar*argv[]) { //printf ("Hello world!\n"); inta[Ten] = {7,3,2,9,8,5,1,Ten,4,6}; intLen =Ten; QuickSort* quicksort=NewQuickSort (A, Len); Quicksort-sort (); PrintArray (A, Len,"QuickSort:"); System ("Pause");//used to pause return 0;}
sorting algorithm (1) Quick sort C + + implementation