java实现快速排序

 java实现一个快速排序的算法,代码比好好理解,效率什么的不考虑了.

快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

 1 public class QuickSort {
 2 
 3     static List<Integer> unSortItems = Arrays.asList(11, 2, 3, 1, 9, 5, 1, 10);
 4     static List<Integer> sortItems = new ArrayList<Integer>();
 5 
 6     static void sort(List<Integer> items) {
 7         int midIndex = items.size() / 2; //取集合中间的数作为比较数.
 8         int midValue = items.get(midIndex);
 9         List<Integer> lowLst = new ArrayList<Integer>(); //创建两个集合保存比中间数小的和大的数.
10         List<Integer> highLst = new ArrayList<Integer>();
11         for (int j = 0; j < items.size(); j++) {
12             if (j == midIndex) //略过自己
13                 continue;
14             Integer curValue = items.get(j);
15             if (curValue <= midValue) {
16                 lowLst.add(curValue);
17             }
18             if (curValue > midValue) {
19                 highLst.add(curValue);
20             }
21         }
22         //把中间数放到较小的集合里
23         if (lowLst.size() < highLst.size())
24             lowLst.add(midValue);
25         else
26             highLst.add(midValue);
27 
28         //拆封到只剩一个数时候结束迭代,并保存结果值到sortItems.
29         if (items.size() <= 1) {
30             sortItems.addAll(items);
31             return;
32         }
33         //分别迭代大小数集合
34         QuickSort.sort(lowLst);
35         QuickSort.sort(highLst);
36 
37     }
38 
39     public static void main(String[] args) {
40         QuickSort.sort(QuickSort.unSortItems);
41         System.out.println(QuickSort.sortItems);
42     }
43 }

 

posted @ 2017-03-14 15:20  java林森  阅读(1136)  评论(0)    收藏  举报