码迷,mamicode.com
首页 > 编程语言 > 详细

java 快速排序 ,用nio里的IntBuffer实现,

时间:2017-03-15 10:32:40      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:pac   截取   过程   i++   res   static   lan   选择   .so   

 java实现一个快速排序的算法,用nio里的IntBuffer实现,

IntBuffer提供了slice,position,capacity等方法可以很方便的操纵数组.用来做排序很是方便.

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

 

 1 public class QuickSort {
 2 
 3     static void sort(IntBuffer items, IntBuffer resultItems) {
 4         if (items.capacity() == 1) { // 拆分到只剩1个元素时停止迭代,保存数据到结果队列
 5             resultItems.put(items.get());
 6             return;
 7         }
 8         int midPos = items.capacity() / 2; // 从数组的中间选择一个数进行二分
 9         int midValue = items.get(midPos);
10         IntBuffer lowItems = IntBuffer.allocate(items.capacity());
11         IntBuffer highItems = IntBuffer.allocate(items.capacity());
12         for (int i = 0; i < items.capacity(); i++) {
13             if (i == midPos)
14                 continue;// 跳过自己
15             int curValue = items.get(i);
16             if (curValue <= midValue) {
17                 lowItems.put(curValue);
18             } else {
19                 highItems.put(curValue);
20             }
21         }
22         // 把选的比较数放入较小的集合中,防止死循环
23         if (lowItems.position() < highItems.position())
24             lowItems.put(midValue);
25         else
26             highItems.put(midValue);
27         lowItems.flip();// 截取有效的数据
28         lowItems = lowItems.slice();
29         highItems.flip();
30         highItems = highItems.slice();// 截取有效数据
31         if (lowItems.capacity() > 0) {
32             QuickSort.sort(lowItems, resultItems);
33         }
34         if (highItems.capacity() > 0) {
35             QuickSort.sort(highItems, resultItems);
36         }
37     }
38 
39     public static void main(String[] agrs) {
40         IntBuffer sourceItems = IntBuffer.wrap(new int[] { 5, 2, 10, 1, 3, 8, 5, 6, 1 });
41         IntBuffer resultItems = IntBuffer.allocate(sourceItems.capacity());
42         QuickSort.sort(sourceItems, resultItems);
43         System.out.println(Arrays.toString(resultItems.array()));
44     }
45 }

 

java 快速排序 ,用nio里的IntBuffer实现,

标签:pac   截取   过程   i++   res   static   lan   选择   .so   

原文地址:http://www.cnblogs.com/reachlins/p/6552829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!