has been in contact with the fast sorting algorithm, the interview has repeatedly been asked, although understand its principle, but never really use the code to knock out.
Write about the algorithm before the code must be the principle to understand, or is blind, in reference to the relevant information and their own meditation, write the following code, some bugs in the middle, but are quickly resolved
If there is a better optimization algorithm, please do not hesitate to enlighten ....
Source:
Package com.zken.test; /** * @author Iamzken * Sorting algorithm * Use the quick sort algorithm to sort an array from small to large * 2015-8-27 13:40/public class Sorter {//Get the intermediate index, the index corresponding to the keyword to divide the array Is the left and right two parts, where the left side is smaller than the key corresponding to the index, and the right-hand one is larger than the key of the index corresponding to the keyword large public static int getmiddle (int[] A, int left, int. right) {//random take a keyword, here le
FT index corresponding to the keyword, equivalent to the location of the left index was dug up a "pit", need the following program to fill this "pit" int key = A[left]; Critical conditions while (left < right) {//When right > Down && a[right] > key indicates that the current right index corresponds to a key that is larger than keys and does not need to be exchanged while (
Right > Left && A[right] > key {right--;
}//program can be executed here to explain the current right index of the corresponding key words smaller than key, need to exchange, that is, "pit" a[left] = A[right]; When left < right && A[left] < key indicates that the key for the current index is smaller than keys and does not need to be swapped while (on right < right && A[left) ;
Key) {left++;
}//program can be executed here to show that the current left index of the corresponding key is larger than keys, need to exchange, that is, "pit" a[right] = A[left];
}//program out of the while loop, that left is equal to right, the following two sentences can also be changed to A[right]=key;return right;
A[left] = key;
return to left; public static void QuickSort (int[] A, int left, int right) {//Critical condition
if (left < right) {//Get intermediate index int middle = Getmiddle (A, left, right);
Recursive ordering of the left sub array quickSort (A,LEFT,MIDDLE-1);
Recursive ordering of the right-hand sub array quickSort (A, middle+1, right);
}//test program public static void Main (string[] args) {int[] a = new int[]{9,3,7,8,2,0,6};
SYSTEM.OUT.PRINTLN ("Array before a quick sort:");
int i = 0;
while (I < a.length) {System.out.print (a[i]+ "T");
i++;
} System.out.println ();
Sorter.quicksort (A, 0, a.length-1);
System.out.println ("Fast sorted array:");
i = 0;
while (I < a.length) {System.out.print (a[i]+ "T");
i++; }
}
}
Execution results:
Arrays before a quick sort:
9 3 7 8 2 0 6
Fast sorted Array:
0 2 3 6 7 8 9