Partition函数
来源:互联网 发布:java内存泄露场景 编辑:程序博客网 时间:2024/05/22 01:34
快排中核心的方法应该算是Partition函数了,它的作用就是将整个数组分成小于基准值的左边,和大于基准值的右边。
普通的Partition函数是这样的:
public static int partition1(int[] array,int lo,int hi){ //以第一个值为基准值,当然你也可以3取1, int key=array[lo]; while(lo<hi){ while(array[hi]>key&&hi>lo){//从后半部分向前扫描 hi--; } array[lo]=array[hi]; while(array[lo]<=key&&hi>lo){//从前半部分向后扫描 lo++; } array[hi]=array[lo]; } array[hi]=key; return hi; }public static void main(String[] args) { int[] a = {34,2,25,1,12,34,12,56,23,15,34,67,89,54,34}; partition2(a, 0, 14); for(int i=0; i<a.length; i++) { System.err.print(a[i]+" "); } }打印的结果是:34 2 25 1 12 34 12 34 23 15 **34** 67 89 54 56 看出来没,大家都是相同的基准值34是各自分开的,我们希望得结果应该是这样的:25 1 12 12 23 15 34 34 34 34 89 54 67 56 这样的好处是相同的值,在后续的遍历过程中,不用再比较一次了。
(左程云,左神写的)
牛逼的Partition函数是这样的:
public static int[] partition1(int[] arr, int begin, int end, int pivotValue) { int small = begin - 1; int cur = begin; int big = end + 1; while (cur != big) { if (arr[cur] < pivotValue) { swap(arr, ++small, cur++); } else if (arr[cur] > pivotValue) { swap(arr, cur, --big); } else { cur++; } } int[] range = new int[2]; range[0] = small + 1; range[1] = big - 1; return range; }public static void main(String[] args) { int[] a = {34,2,25,1,12,34,12,56,23,15,34,67,89,54,34}; int[] b = partition1(a,0,14,34); System.out.println(b[0]); System.out.println(b[1]); for(int i=0; i<a.length; i++) { System.err.print(a[i]+" "); } }输出的结果是:7 //相同基准值的起始索引10 //相同基准值的末尾索引2 25 1 12 12 23 15 **34 34 34 34** 89 54 67 56 这样,你下一次递归直接就可以避免重复比较相同的基准值了。
阅读全文
0 0
- partition函数
- Partition函数
- partition函数
- Partition函数
- 分析函数partition by
- partition函数的实现
- 快排中partition函数-java
- over partition by 函数
- 基本算法-partition函数
- Python的partition字符串函数
- oracle rank,over partition 函数
- OVER(PARTITION BY)函数介绍
- OVER(PARTITION BY)函数介绍
- Python的partition字符串函数
- OVER(PARTITION BY)函数介绍
- OVER(PARTITION BY)函数介绍
- OVER(PARTITION BY)函数介绍
- OVER(PARTITION BY)函数介绍
- 数组模拟链表之P1160 队列安排
- Day8-27.Literals
- Spark以及生态圈介绍
- EasyStream系列1之rtsp转rtmp
- itext实现word转pdf,添加水印倾斜铺满全屏,禁止修改和复制
- Partition函数
- 剑指offer--链表中环的入口结点
- photoshop注册机,这个必须留下来
- tools:replace="android:icon, android:theme"
- 《程序员的修炼之道》笔记——4、足够好的软件
- shell 输入/输出重定向
- 进程间通信之消息队列
- 大数据Spark企业级实战版【学习笔记】----Spark速度为何如此快
- QT将信息保存到某个路径下(1)