Quick Sort function Template
During this time, I was obsessed with STL and made some research. Today I wrote a new quick sorting algorithm using the template function and posted the code to share it.
There are two versions. Version 2 can pass in the comparator and define the sorting rules by yourself.
Quick Sorting Algorithm ideas:
1) Select an element from the sequence as the benchmark;
2) Rearranging the sequence. All the elements smaller than the benchmark are on the left of the benchmark. The elements larger than the benchmark are on the right of the benchmark, and the elements equal to the benchmark are on any side. This process is called grouping;
3) recursively sort groups smaller than the benchmark and those larger than the benchmark respectively.
# Include
# Include
// Print the function template
Void print (iterator begin, iterator end) {while (begin! = End) cout <* begin ++ <''; cout <endl;} // exchange function template
Void my_swap (type & a, type & B) {type c = a; a = B; B = c ;}// quick sort function template, Version 1 template
Void my_sort (iterator begin, iterator end) {iterator p = begin; iterator last = end; // point to the next position at the end -- last; for (iterator I = begin, j = last; i! = J;) {while (! (I = p | * p <* I) ++ I; if (I! = P) {my_swap (* p, * I); // The switch location, which cannot be assigned here, because the data type p = I;} while (! (J = p | * j <* p) -- j; if (j! = P) {my_swap (* p, * j); p = j ;}} iterator it = begin; ++ it; if (p! = Begin & p! = It) // recursive my_sort (begin, p); it = p; ++ it; if (it! = End & it! = Last) // recursive my_sort (it, end);} // the template of the quick sort function that is greater than the benchmark. Version 2 (the comparator is higher than the version, and the template is the same as the other)
Void my_sort (iterator begin, iterator end, comparator cmp) {iterator p = begin; iterator last = end; -- last; for (iterator I = begin, j = last; I! = J;) {while (! (I = p | cmp (* p, * I) ++ I; if (I! = P) {my_swap (* p, * I); p = I;} while (! (J = p | cmp (* j, * p) -- j; if (j! = P) {my_swap (* p, * j); p = j ;}} iterator it = begin; ++ it; if (p! = Begin & p! = It) my_sort (begin, p, cmp); it = p; ++ it; if (it! = End & it! = Last) my_sort (it, end, cmp) ;}// comparator class CmpInt {public: bool operator () (int a, int B) const {return a> B ;}}; int main (void) {int na [] = {13, 24, 22, 19, 44, 56, 88, 22}; vector
Vi (na, na + 8); // vector list
Li (na, na + 8); // list my_sort (na, na + 8); // test array print (na, na + 8); my_sort (vi. begin (), vi. end (); // test vector print (vi. begin (), vi. end (); my_sort (li. begin (), li. end (), CmpInt (); // test list print (li. begin (), li. end (); return 0 ;}