Quick Sort (Quicksort) is an improvement to the bubbling sort. Quick Sort by C. A. R. Hoare was introduced in 1962. Its basic idea is: by a trip to sort the data to be sorted into two separate parts, one part of all the data is smaller than the other part of all the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence. First, let's look at the classic quick-line:
Which is less than equal to the area can be optimized, less than the area is less than the place equal to the area, greater than the magnification in the region. Can take advantage of the Dutch flag issue
Question of the flag of the Netherlands:
Given an array of arr, and a number num, place the number less than Num on the left side of the array, the number equal to num placed in the middle of the array, and the number greater than num on the right side of the array.
This is the Dutch flag problem, the general process
The code is as follows
Public classCode5_netherlandsflag { Public Static int[] Partition (int[] arr,intLintRintnum) { intless = L-1; intmore = R + 1; while(L <More ) { if(Arr[l] <num) {Swap (arr,++less, l++); } Else if(Arr[l] >num) {Swap (arr,--More , L); } Else{L++; } } return New int[] {less + 1, more-1 }; } Public Static voidSwapint[] arr,intIintj) {intTMP =Arr[i]; Arr[i]=Arr[j]; ARR[J]=tmp; }}
The optimized fast-line code is:
Public Static voidQuickSort (int[] arr) { if(arr = =NULL|| Arr.length < 2) { return; } quickSort (arr,0, Arr.length-1); } Public Static voidQuickSort (int[] arr,intLintr) {if(L <r) {swap (arr, l+ (int) (Math.random () * (R-l + 1) ), R); int[] p =partition (ARR, L, R); QuickSort (arr, L, p[0]-1); QuickSort (arr, p[1] + 1, R); } } Public Static int[] Partition (int[] arr,intLintr) {intless = L-1; intmore =R; while(L <More ) { if(Arr[l] <Arr[r]) {Swap (arr,++less, l++); } Else if(Arr[l] >Arr[r]) {Swap (arr,--More , L); } Else{L++; }} swap (arr, more, R); return New int[] {less + 1, more}; } Public Static voidSwapint[] arr,intIintj) {intTMP =Arr[i]; Arr[i]=Arr[j]; ARR[J]=tmp; }
Where swap (arr, l + (int) (Math.random () * (R-l + 1)), R); This sentence is to make the fast row affected by the data state into a probabilistic, random
Quick Sort (classic fast and random fast)