Today, say a quick sort:
Basic idea:
- Take one element (e.g. first) as Pivot point
- All elements smaller than it are placed before it, and the elements larger than it are placed, forming a left and right two sub-tables
- Re-select the central element for each child table and adjust it to this rule until the elements of each child table are left only one
Attention:
- The sub-table of each trip is formed by alternating approximation method from two to the middle.
- Recursive algorithm can be used because the operation of each sub-table is similar in each trip
Code implementation:
#include <iostream>using namespace STD;///Find the first pivot point, which is bounded by this pivot point, dividing the array to be sorted into//[low,pivot), [pivot], (Pivot,high] three partsintPartition (intA[],intLowintHigh) {if(Low > High)//Judging illegal conditions return-1;intPivot = A[low];//Pivot point defaults to the first element of the array A[low] (backup) while(Low < High)//scan from both ends of the array alternately to the middle{ while(Low < High && pivot <= A[high])//On the premise of not less than pivot{high--;//Extend right terminal sequence to the left} A[low] = A[high];//values less than pivot are grouped into left sub-sequence while(Low < High && pivot >= A[low])//On the premise of not being less than pivot{low++;//Extend left terminal sequence to the right} A[high] = A[low];//values greater than pivot are grouped into the right sub-sequence} A[low] = pivot;//Put the pivot point record of the backup between the left and right sub-sequences returnLow//Return the subscript of the pivot point}//Fast Algorithm (recursive)voidQuickSort (intA[],intLowintHigh) {if(High-Low <2)//Only one value is ordered by default, no need to sort{return; }intKey = Partition (A,low,high);//Find the subscript of the pivot pointQuickSort (a,low,key-1);//recursion to sort. Once the pivot point is found, the pivot point can be determined.QuickSort (a,key+1, high);//The position is the sorted position, so you don't have to sort. }/ *------Test Code------* /intMain () {//int a[] = {1,2,4,3,12,45,2,54,6,32,44}; intA[] = { +, +, Wu,6,3, -,5,5, $, -};intLa =sizeof(a)/sizeof(a[0]) -1;//must be reduced by one because the array subscript is starting from 0, otherwise it will cause the array to go out of boundsQuickSort (A,0, La); for(inti =0; I <= La; i++) {cout<<a[i]<<endl; }return 0;}
Output Result:
Time Efficiency: O (nlog2n)-an exponential increase in the number of elements determined per trip
Space Efficiency: O (log2n)-Recursive to use the stack space
Stability: unstable-an element can be elected as a fulcrum.
Data structure--fast sorting algorithm