The basic idea of fast sorting is: to split the pending records into two separate parts through a sort of sequence, in which some of the recorded keywords are smaller than those of the other records, then the two parts of the records can be sorted and ordered sequentially.
Fast sorting is an unstable sorting method with an average time complexity of: O (Nlogn), and the worst case is O (n*n)
Special Note: The partition function used in the quick sort, its function is to carry on a quick order, return "reference target" the final position p, after partition processing, p left the record keyword is not larger than the reference target, p right of the record keyword is not less than the reference target. The partition function is also useful for finding the largest or smallest K records in an array.
The C + + code is as follows:
#include <iostream>#include <vector>#include <stack>using namespace STD;Template<TypeNameComparable>intPartition vector<Comparable>&vec,intLowintHigh) {Comparable pivot = Vec[low]; while(Low while(Low while(Low returnLow;}//Use recursive quick sortTemplate<TypeNameComparable>voidQuicksort1 ( vector<Comparable>&vec,intLow,intHigh) {if(Low intMID = partition (VEC, Low, high); Quicksort1 (VEC, Low, mid-1); Quicksort1 (VEC, Mid +1, high); }}//actually is to use the stack to save each of the first and last elements of the string to be sorted subscript, the next while loop out of this range, the partition operation of this sequence,//Each received Mid is the final position of the vector, knowing that the stack does not need to be put in, there is no data when the loop endsTemplate<TypeNameComparable>voidQuicksort2 ( vector<Comparable>&vec,intLowintHigh) { Stack<int>Qtyif(LowintMID = partition (VEC, Low, high);if(low<mid-1) {St.push (low); St.push (Mid-1); }if(mid+11); St.push (high); } while(!st.empty ()) {intQ = St.top (); St.pop ();intp = st.top (); St.pop (); MID = partition (VEC, p, q);if(p<mid-1) {St.push (P); St.push (Mid-1); }if(mid+1<Q) {St.push (Mid +1); St.push (q); } } }}int_tmain (intARGC, _tchar* argv[]) {inta[Ten] = { A, +, -,4, -, +, in, the,111,9}; vector<int>VEC (A, A +Ten);intLen = Vec.size ();//quicksort1 (VEC, 0, len-1);Quicksort2 (VEC,0, Len-1); for(intI=0; I < len;i++) {cout<< vec[i]<< Endl; } System ("Pause");return 0;}
Recursive and non-recursive implementation of fast sequencing-----C + + code implementation