Fast sorting, average run time O (n log n), worst run time O (n^2).
I think it's easier to see the Python version of the quick-release algorithm (http://www.cnblogs.com/fcyworld/p/6160558.html) first.
Overall idea:
First, a value pivot is selected from the array, then the array is divided into two parts according to the value pivot, and then to the two sections respectively.
Take advantage of the quick row.
Specific details:
1. In the specific implementation, because the choice of pivot will have a large impact on the division of the array, if the division of the imbalance, it will greatly affect
Sort time. To eliminate this effect as much as possible, take the index in the array to 0,n-1, and the middle value in the median as pivot. Produce
Pivot, the value of the 0,n-1 position has been satisfied with the requirements of the pivot, so the sorting time does not need to be considered, so the value of the pivot is guaranteed
The n-2 position.
2. In order to divide the array into two parts, a double pointer i,j is used. I brushed back from the value less than pivot, J
Value that, when I,j is stopped, swaps the value at the point where the I,j is located.
3. In a small array (the size of a group <cutoff), the efficiency of the fast row is not high, so the small group of time using the insertion sort
1 voidQuicksortint*nums,intN)2 {3QS (Nums,0, N-1);4 }5 voidQsint*nums,intLeftintRight )6 {7 intPV;8 inti,j;9 intcutoff=Ten;Ten if(left+cutoff<=Right ) One { Apv=mid3 (nums,left,right); -I=Left ; -j=right-1; the while(1) - { - while(nums[++i]<PV); - while(nums[--j]>PV); + if(i<j) - swap (nums[i],nums[j]); + Else A Break; at } -Swap (nums[i],nums[right-1]); - QS (nums,left,i); -QS (nums,i+1, right); - } - Else inIntersort (nums+left,right-left+1); - } to intMID3 (int*nums,intLeftintRight ) + { - intCenter= (left+right)/2; the if(nums[left]>Nums[center]) * swap (Nums[left],nums[center]); $ if(nums[left]>Nums[right])Panax Notoginseng swap (nums[left],nums[right]); - if(nums[center]>Nums[right]) the swap (nums[center],nums[right]); +Swap (nums[center],nums[right-1]); A returnnums[right-1]; the } + voidSwapint&m,int&N) - { $m^=N; $n^=m; -m^=N; - } the voidIntersort (int*nums,intN) - {Wuyi inti,j; the inttmp; - for(i=1; i<n;i++) Wu { -tmp=Nums[i]; About for(j=i;j>0&&tmp<nums[j-1];j--) $nums[j]=nums[j-1]; -nums[j]=tmp; - } -}
"Sort" QuickSort