Quick Sorting Algorithm and Sorting Algorithm
In the previous article, I wrote the implementation process of the heap sorting algorithm. Today I am doing code exercises on the fast sorting algorithm.
In terms of fast sorting, his main idea is to rationally divide a series. The criteria for Division come from the selection of pivot, where pivot is used to draw the molecular sequence and generate recursive expressions, the subsequence is obtained, and the whole sequence is consistent by exchanging data.
Therefore, pivot selection is a fundamental requirement for improving the efficiency of the quick sorting algorithm.
Without talking nonsense, the basic idea of fast sorting has already been touched by in the data structure book. The specific implementation is as follows:
# Include <iostream> using namespace std; template <class Any> void SwapData (Any & a, Any & B) {Any tmp = a; a = B; B = tmp ;} template <class AnyType> void OutPut (AnyType array, int len) {cout <array [0]; for (int I = 1; I <len; I ++) the core idea of cout <"<array [I]; cout <endl;}/* fast sorting is how to select the Pivot Position, that is, how to reasonably divide the entire series. The essence of Improving the algorithm for fast sorting is to improve the division of sequences. */Template <class AnyType> void QuickSort (AnyType array [], int left, int right, int len) {if (left <right) {AnyType tmp = array [left]; int I = left; int j = right + 1; while (true) {while (I + 1 <len & array [++ I] <tmp ); while (J-1>-1 & array [-- j]> tmp); if (I> = j) break; SwapData (array [I], array [j]);} array [left] = array [j]; array [j] = tmp; QuickSort (array, left, J-1, len); QuickSort (array, j + 1, right, len) ;}} template <class AnyType> int MyPartition (AnyType array [], int left, int right) {AnyType tmp = array [right]; int I = left-1; for (int j = left; j <right; j ++) {if (array [j] <= tmp) SwapData (array [++ I], array [j]);} SwapData (array [I + 1], array [right]); return I + 1 ;} template <class AnyType> void QuickSortMoreFast (AnyType array [], int left, int right) {if (left <right) {int q = MyPartition (array, left, right ); quickSortMoreFast (array, left, q-1); QuickSortMoreFast (array, q + 1, right );}} // call the C ++ internal function for sorting # include <algorithm> # include <vector> void InnerQSort () {vector <int> data; for (int I = 0; I <50; I ++) data. push_back (rand (); sort (data. begin (), data. end (); OutPut (data, data. size ();} int main () {// int array [] = {5, 4, 7, 3, 9, 1, 8, 6, 10, 2}; // QuickSort (array, 0, sizeof (array)/sizeof (int), sizeof (array)/sizeof (int); // QuickSortMoreFast (array, 0, sizeof (array)/sizeof (int )); // OutPut (array, sizeof (array)/sizeof (int); InnerQSort (); return 0 ;}