"Turn" http://blog.csdn.net/wangkuifeng0118/article/details/7286332
Ashamed to say, yesterday read someone else's blog above a number of algorithms, in fact, these algorithms have been studied in the university, but almost all forgotten. Although now do Java upper Development basically does not use the algorithm, but still is the feeling algorithm is a kind of thought, is a kind of soul, so also not only opened the Min teacher's data structure, one one to the previously forgotten algorithm realization once.
The basic idea of quick sorting :
Divide the records to be sorted into separate two parts by a single pass, where some of the recorded keywords are smaller than the other, and then the two sections continue to be sorted until the entire sequence is ordered.
First look at this picture:
Think of the whole sequence as an array, the 0th position as the middle axis, and the last one, if it is smaller than it, does not do any processing than it; The end is exchanged again and the smaller one, than it is smaller than that, which does not exchange much larger than it. This cycle, a trip to the completion of the order, the left side is smaller than the middle axis, the right is larger than the middle axis, and then the division of the method, respectively, the two separate array to sort.
[HTML]View Plaincopy
- public int getmiddle (integer[] list, int. Low, int.) {
- int tmp = List[low]; The first of the arrays as a middle axis
- while (Low < high ) {
- while (Low < high && List[high] > tmp) {
- high--;
- }
- List[low] = List[high]; Less than mid-axis records moved to the low end
- while (Low < high && List[low] < tmp) {
- low++;
- }
- List[high] = List[low]; A record larger than the middle axis moves to the high end
- }
- List[low] = tmp; Middle axis record to tail
- return low; Returns the position of the middle axis
- }
Recursive form of sorting algorithm:
[HTML]View Plaincopy
- public void _quicksort (integer[] list, int. Low, int.) {
- if (Low < high ) {
- int middle = getmiddle (list, low, high); Divides a list array into a split
- _quicksort (list, low, middle-1); Recursive ordering of low-word tables
- _quicksort (list, middle + 1, high); Recursive ordering of high-character tables
- }
- }
[HTML]View Plaincopy
- public void Quick (integer[] str) {
- if (Str.length > 0) {//See if the array is empty
- _quicksort (str, 0, str.length-1);
- }
- }
To write a test method:
[HTML]View Plaincopy
- public class Testmain {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- TODO auto-generated Method Stub
- Integer[] list={34,3,53,2,23,7,14,10};
- Quicsort qs=new Quicsort ();
- Qs.quick (list);
- for (int i=0;i<list.length;i++) {
- System.out.print (list[i]+ "");
- }
- System.out.println ();
- }
- }
Look at the print results:
2 3 7 10 14 23 34 53
This sort is good, the quick sort is an improvement on the bubble sort, the average time complexity is O (NLOGN).
Java Quick Sort