【发布时间】:2015-01-10 14:39:52
【问题描述】:
我正在做的是使用快速排序算法,以便我的枢轴元素(它将始终是数组的第一个元素)定位到已排序数组中的适当位置,并且我再次调用此方法,直到我这样做不将元素定位在给定的等级。有更好的解决方案吗?
这是我的代码:
public static int arbitrary(int a[],int x,int y,int rank)//x and y are first and last indecies of the array
{
int j=y,temp;
if(x<y)
{
for(int i=y;i>x;i--)
{
if(a[i]>a[x])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
j--;
}
}
temp=a[x];
a[x]=a[j];
a[j]=temp;
//System.out.println("j is "+j);
if(j==rank)
return a[j];
else if(rank<j)
return arbitrary(a,x,j-1,rank);
else
return arbitrary(a,j+1,y,rank);
}
else
return 0;
}
【问题讨论】:
-
排名元素是什么意思?
-
如果“rank”是指“排序后元素在数组中的位置”,构造一个minheap并用它来查找第N大元素。
-
@Kevin 是的,这就是我所说的排名。您能否详细说明您的答案,因为我不完全了解 minheap 如何帮助我,因为在构建 minheap 后我可以知道所有最大的 n/ 2 个元素在叶子中,仅此而已...感谢您的回复