排序算法(四)

这有篇不错的介绍“快速排序”的博客:http://www.cnblogs.com/morewindows/archive/2011/08/13/2137415.html

以下是Java代码

 1 public class QuickSort {
 2     public static void main(String[] args) {
 3         int[]  a = {4, 2, 1, 6, 3, 0, -5, 1, 1};
 4         qsort_asc(a, 0, a.length - 1);
 5         
 6         for (int i = 0; i < a.length; i++) {
 7             System.out.printf("%d ", a[i]);
 8         }
 9     }
10     
11     public static void qsort_asc(int source[], int low, int high) {
12         int i, j, x;
13         if(low < high){
14             i = low;
15             j = high;
16             x = source[i];
17             while(i < j){
18                 //从后往前查找比  x 小的数,找到后填到 source[i] 处,并且i+1,source[j]处为坑
19                 while(i < j && source[j] > x){
20                     j--;
21                 }
22                 if(i < j){
23                     source[i] = source[j];
24                     i++;
25                 }
26                 //从前往后查找比 x 大的数,找到后填到source[j]处,并且j-1,source[i]处为坑
27                 while( i < j && source[i] < x){
28                     i++;
29                 }
30                 if(i < j){
31                     source[j] = source[i];
32                     j--;
33                 }
34             }
35             source[i] = x;
36             qsort_asc(source, low, i - 1);
37             qsort_asc(source, i + 1, high);
38         }
39     }
40 }

 

posted @ 2014-03-11 14:23  soul390  阅读(202)  评论(0)    收藏  举报