It is said that the general test or interview will be the test of the order, today try to realize their own, see the principle, found not so easy, and went online to find the next, found that the author's code has a problem. This has aroused my interest more.
Then insisted on writing out and tested, there should be no problem, if there are questions want to comment
The evaluation of the theory and algorithm of the fast sorting is not pasted, online a large pile, in this only write code
1 Public classQuickSort {2 @Test3 Public voidsort () {4 int[] A = {5, 8, 6, 2, 7, 9, 1, 7, 3 };5 //int[] A = {3, 1, 2, 5, 7, 9, 6, 4, 8};6 7Sort (A, 0, a.length-1);8 System.out.println (Arrays.tostring (a));9 }Ten One Private voidSortint[] A,intStartintend) { A intI=start; - intj=end; - intKey =A[i]; the inttmp; - while(J > I) {//Traverse left - while(J > I && a[j] >=key) -j--; + if(A[j] <key) { -TMP = A[j];//key exists in the a[j] +A[J] =A[i]; AA[i] =tmp; at } - while(J > I && a[i] <=key) -i++; - if(A[i] >key) { -TMP =A[i]; -A[i] =A[j]; inA[J] =tmp; - } to } + if(j<end) Sort (a,j+1, end); - if(i>start) Sort (a,start,i-1); the } * $}
Tell me a few questions that I think are important:
- The parameter start,end of sort () is assigned to I,J. Because we are going to swap the elements in the array by subscript. And finally we need to use the start,end. So you can't use start,end directly.
- The idea is simply to start the key from the right to the left, as long as there is less than the key element, that is, the exchange, and then from left to right, the element exchange is greater than the key
- Note In the process of exchange, to understand that the key is constantly changing position.
- The last i,j should be equal, jumping out of the outermost while loop
- And then recursively call sort
I met the pit, originally intended to try the 123456789, the result array hit two 7, there was a dead loop, and later found that 23 lines did not write >= (30 lines did not write <=). Hope the beginner reader can understand why to add equal sign ~
The Java implementation of fast sequencing