一看就懂的快速排序方法_java版

运行效果:

=================================================

代码部分:

=================================================

/hello_test/src/com/b510/test/QuickStore.java

 1 /**
 2  * 
 3  */
 4 package com.b510.test;
 5 
 6 /**
 7  * 快速排序
 8  * @author <a href="mailto:hongtenzone@foxmail.com">hongten</a>
 9  * @date 2013-3-1
10  * 更多信息:<a href="http://www.cnblogs.com/morewindows/archive/2011/08/13/2137415.html">more>></a>
11  */
12 public class QuickStore {
13     /**
14      * 创建随机数组
15      * @param min 数组的最小值
16      * @param max 数组的最大值
17      * @param length 数组的长度
18      * @return 随机数组
19      */
20     public static int[] createArray(int min, int max, int length) {
21         int[] array = new int[length];
22         for (int i = 0; i < length; i++) {
23             array[i] = min + (int) (Math.random() * (max - min + 1));
24             System.out.println("随机数 :array[" + i + "] = " + array[i]);
25         }
26         return array;
27     }
28     
29     /**
30      * 快速排序
31      * @param array 源数组
32      * @param l 
33      * @param r
34      * @return
35      */
36     public static int[] quickStore(int[] array, int l, int r) {
37         if (l < r) {
38             int i = l, j = r, x = array[l];
39             while (i < j) {
40                 while (i < j && array[j] >= x)
41                     // 从右向左找第一个小于x的数
42                     j--;
43                 if (i < j)
44                     array[i++] = array[j];
45 
46                 while (i < j && array[i] < x)
47                     // 从左向右找第一个大于等于x的数
48                     i++;
49                 if (i < j)
50                     array[j--] = array[i];
51             }
52             array[i] = x;
53             quickStore(array, l, i - 1); // 递归调用
54             quickStore(array, i + 1, r);
55         }
56         return array;
57     }
58     
59     /**
60      * 显示数组信息
61      * @param array
62      */
63     public static void showArray(int[] array) {
64         System.out.println("排序后....");
65         for (int i = 0; i < array.length; i++) {
66             System.out.println("array[" + i + "] = " + array[i]);
67         }
68     }
69     
70     /**
71      * test
72      * @param args
73      */
74     public static void main(String[] args) {
75         int[] array = createArray(12, 50, 6);
76         int[] newArray = quickStore(array, 0, array.length - 1);
77         showArray(newArray);
78     }
79 }

 

posted @ 2013-03-01 23:32  Hongten  阅读(800)  评论(0编辑  收藏  举报
Fork me on GitHub