java 数据透视表 组件_java – 在数据透视表上对数组进行分区

我试图编写一个简单的算法来移动枢轴周围的元素,使得枢轴左侧的元素小于枢轴,并且枢轴右侧的元素大于它(快速排序中的相同步骤).我编写了可行的代码,但之后我将算法更改为以下内容,但它无效.

算法的想法很简单.

Have two pointers, one at the beginning of the array and one at the end of array. If the elements pointed by i are lesser than pivot, keep skipping it until we find a greater element; and keep decrementing j until we find an element greater than the smaller element. [It is a common algorithm]

现在的代码

private static void sortByPivot(int[] a)

{

Random r = new Random();

int index = r.nextInt(a.length);

int pivot = a[index];

System.out.println("pivot = " + pivot);

int i =0 , j = a.length -1;

while(true)

{

while(a[i] <= pivot) i++;

while( j >0 && a[j] >= pivot) j--;

if(i <= j)

{

break;

}

else{

swap(a,i,j);

}

}

swap(a,i,index); //swap the pivot and the i

}

交换例程:

private static void swap(int[] a, int i , int j)

{

int temp = a[i];

a[i] = a[j];

a[j] = temp;

}

当我使用以下数组运行它时

int[] a = {46,3,8,4,2,6,244,76}

当枢轴被选为4时

输出是

4 3 8 46 2 6 244 76

对于边缘的其他一些枢轴,我得到一个空指针异常.

实施中是否存在任何缺陷.逻辑对我来说似乎是正确的.我已经尝试了很长一段时间,但我无法解决它.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值