Basic idea: 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 according to the method of the two parts of the data are quickly sorted, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.
Example 3 1 5 2 7 9 3 0
First, with 3 as the base number, the base number means that the number is the reference, the other number and its comparison, now for example, there are two people, respectively, from the left and right to find, the right person to find a number 3 smaller than the base number, the left side of the number of people looking for the number of 3, to find the next exchange, the right person first to find, such , the people on the right start from 0, 0:3 small, record this number, the left of the people from 3 to find, find 5:3 big, now put this two number exchange position to get a new array 3 1 0 2 7 9 3 5, the right people continue to repeat the above steps to find 2, the left of the 2 also there is no greater than 3 number, So two people met in the number 2, the benchmark number 3 and this 2 exchange, get a new array 2 1 0 3 7 9 3 5, the 3 as a split point, the entire array is divided into two parts, the left 2 1 0 and the right 7 9 3 Repeat the above steps to continue sorting
The Java code is as follows:
Public classQuickSort { Public Static voidMain (string[] args) {//TODO auto-generated Method StubQuickSort QS=NewQuickSort (); int[] score = {10,9,8,7,6,5,4,3,2,1}; Qs.quicksort (Score,0,score.length-1); for(inti=0;i<score.length;i++) {System.out.print (Score[i]+" "); } } Public voidQuickSort (int[] A,intLeftintRight ) { inti,j,t,temp; if(left>Right )return; I=Left ; J=Right ; Temp=A[left]; while(i!=j) { while(A[j]>=temp && i<j) J--; while(A[i]<=temp && i<j) I++; if(i<j) {T=A[i]; A[i]=A[j]; A[J]=T; }} A[left]=A[i]; A[i]=temp; QuickSort (A,left,i-1); QuickSort (A,i+1, right); }}
Execution Result:
1 2 3 4 5 6 7 8 9
Algorithm Exercise 5---Quick sort Java Edition