java中element_Java中的等效'nth_element'函數是什麼?

這裏是一個Java實現nth_element的:

class Nth_element

{

static void nth_element_helper2(double[] arr, int beg, int end)

{

for(int i = beg + 1; i < end; i++)

{

for(int j = i; j > beg; j--)

{

if(arr[j - 1] < arr[j])

break;

double t = arr[j];

arr[j] = arr[j - 1];

arr[j - 1] = t;

}

}

}

static void nth_element_helper(double[] arr, int beg, int end, int index)

{

if(beg + 4 >= end)

{

nth_element_helper2(arr, beg, end);

return;

}

int initial_beg = beg;

int initial_end = end;

// Pick a pivot (using the median of 3 technique)

double pivA = arr[beg];

double pivB = arr[(beg + end)/2];

double pivC = arr[end - 1];

double pivot;

if(pivA < pivB)

{

if(pivB < pivC)

pivot = pivB;

else if(pivA < pivC)

pivot = pivC;

else

pivot = pivA;

}

else

{

if(pivA < pivC)

pivot = pivA;

else if(pivB < pivC)

pivot = pivC;

else

pivot = pivB;

}

// Divide the values about the pivot

while(true)

{

while(beg + 1 < end && arr[beg] < pivot)

beg++;

while(end > beg + 1 && arr[end - 1] > pivot)

end--;

if(beg + 1 >= end)

break;

// Swap values

double t = arr[beg];

arr[beg] = arr[end - 1];

arr[end - 1] = t;

beg++;

end--;

}

if(arr[beg] < pivot)

beg++;

// Recurse

if(beg == initial_beg || end == initial_end)

throw new RuntimeException("No progress. Bad pivot");

if(index < beg) // This is where we diverge from QuickSort. We only recurse on one of the two sides. This is what makes nth_element fast.

nth_element_helper(arr, initial_beg, beg, index);

else

nth_element_helper(arr, beg, initial_end, index);

}

static double nth_element(double[] arr, int index)

{

nth_element_helper(arr, 0, arr.length, index);

return arr[index];

}

public static void main(String[] args)

{

double[] arr = { 9, 7, 1, 5, 6, 4, 3, 2, 8, 0, 10 };

if(nth_element(arr, 5) == 5)

System.out.println("seems to work");

else

System.out.println("broken");

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值