Algorithm idea:
By setting a sentry, each time compared to the sentry, it is smaller than he on the left, bigger than he on the right. Then the array 0----middle-1 to the left of the sentry, and middle+1-----end to do the same sort.
Complexity of the algorithm:
The quick sort time complexity is O (NLOGN), because it is implemented with substitution on the original array, so no additional storage space is required.
Core code:
1 Public Static voidQuickSort (int[]a,intLowintHigh ) {2 intMiddle;3 if(low<High ) {4Middle =Partition (a,low,high);5QuickSort (a,low,middle-1);6QuickSort (a,middle+1, high);7 }8 }9 Public Static intPartition (int[]arr,intLowintHigh ) {Ten intMiddle =Arr[low]; One inttmp; A while(low<High ) { - while(Lowmiddle) -high--; theTMP =Arr[high]; -arr[high]=Arr[low]; -arr[low]=tmp; - while(Lowmiddle) +low++; -TMP =Arr[high]; +arr[high]=Arr[low]; Aarr[low]=tmp; at } - returnLow ; -}Full code
1 PackageQuickSort;2 //by setting a sentry, each time compared to the sentry, it is smaller than he on the left, bigger than he on the right. 3 //then the array 0----middle-1 to the left of the sentry, and middle+1-----end to do the same sort. 4 Public classSort {5 Static intArrtest1[] = {4,3,7,8,0,9,1,2,6,5};6 intArrtest2[] = {0,1,2,3,4,5,6,7,8,9};7 intArrtest3[] = {9,8,7,6,5,4,3,2,1,0};8 Public Static voidMain (String args[]) {9 display (arrtest1);TenQuickSort (arrtest1,0,arrtest1.length-1); One display (arrtest1); A } - Public Static voidQuickSort (int[]a,intLowintHigh ) { - intMiddle; the if(low<High ) { -Middle =Partition (a,low,high); -QuickSort (a,low,middle-1); -QuickSort (a,middle+1, high); + } - } + Public Static intPartition (int[]arr,intLowintHigh ) { A intMiddle =Arr[low]; at inttmp; - while(low<High ) { - while(Lowmiddle) -high--; -TMP =Arr[high]; -arr[high]=Arr[low]; inarr[low]=tmp; - while(Lowmiddle) tolow++; +TMP =Arr[high]; -arr[high]=Arr[low]; thearr[low]=tmp; * } $ returnLow ; Panax Notoginseng } - Public Static voidDisplayint[]a] { the for(inti=0;i<a.length;i++){ +System.out.print (a[i]+ ""); A } the System.out.println (); + } -}
Run results
Quick Sort (Java)