Fast Sorting Algorithm (principle and implementation) and sorting algorithm principle implementation
Introduction:
Quicksort is an improvement in Bubble sorting. Proposed by C. A. R. Hoare in 1962. Its basic idea is: Split the data to be sorted into two independent parts by one sort, and all the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence.
Algorithm idea:
Set the array to be sorted to A [0]... A [N-1], first randomly select A data as standard (usually the last number of the array) as the key data, and then put all the smaller than it before it, all the numbers larger than it are placed behind it (in fact, as long as all the elements smaller than it are placed before it, the next condition is automatically met ), this process is called quick sorting. It is worth noting that quick sorting is not a stable sorting algorithm, that is, the relative positions of multiple identical values may change at the end of the algorithm. (Source: Baidu encyclopedia)
C ++ implementation:
# Include <iostream> # include <stdlib. h> # include <time. h> using namespace std; bool initArray (int * Array, int arraySize) {// initialize Random Seed srand (time (NULL); for (int I = 0; I! = ArraySize; ++ I) {// assign an Array with a random number Array [I] = rand ();} return true;}/* Division function: so that the elements before Array [I + 1] are smaller than the elements of this element in Array [I + 1] are smaller than this element */template <typename T, typename Index_t> Index_t partition (T * Array, Index_t prev, Index_t tail) {T standard = Array [tail]; Index_t I = prev-1; // The numbers before I and I are smaller than standard for (Index_t j = prev; j! = Tail; ++ j) {// any element of the array, as long as it is smaller than or equal to standard, it is switched to the first half of the array // (therefore, the second half of the Array is an element greater than standard.) if (Array [j] <= standard) {++ I; swap (Array [I], Array [j]);} swap (Array [I + 1], Array [tail]); // return I + 1;} template <typename T, class Index_t> void quickSort (T * Array, Index_t prev, Index_t tail) {if (prev <tail) {Index_t q = partition (Array, prev, tail ); // The first half of the Array is divided into quickSort (Array, prev, q-1); // logarithm The second half of the group is divided into quickSort (Array, q + 1, tail) ;}} int main () {int arraySize = 10; int * Array = new int [arraySize]; initArray (Array, arraySize); quickSort (Array, 0, arraySize-1); for (int I = 0; I! = ArraySize; ++ I) {cout <Array [I] <endl;} delete Array ;}