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

 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 }

 

转载于:https://www.cnblogs.com/reachlins/p/6552829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值