我一直在尝试找出如何正确使用快速选择算法以o(n)的效率找到数组的中位数。我已经尝试过将其编码,但找不到正确的中位数。我只是对我正在做的事情有些停滞,需要改变以找到正确的中位数。
这是我到目前为止的代码。
public static void main(String args[])
{
int count = 0;
Scanner in = new Scanner (System.in);
int houses = in.nextInt();
ArrayList <Integer> array = new ArrayList <Integer>();
while (count < houses)
{
array.add(in.nextInt());
count++;
}
System.out.println(median(array, houses));
in.close();
}
public static int median (ArrayList <Integer> array, int k)
{
int median = 0;
int lpos = 0;
int rpos = 0;
int pivot = k/2;
int length = k/2;
ArrayList <Integer> leftArray = new ArrayList <Integer>();
ArrayList <Integer> rightArray = new ArrayList <Integer>();
if (array.size() == 1)
{
return array.get(0);
}
else if (array.size() < pivot)
{
return array.get(pivot);
}
else
{
for (int i=0; i < array.size()-1; i++)
{
if (array.get(i) <= array.get(pivot))
{
leftArray.add(array.get(i));
lpos++;
}
else
{
rightArray.add(array.get(i));
rpos++;
}
}
if (leftArray.size() == length)
{
return array.get(pivot);
}
else if (leftArray.size() > length)
{
return median(leftArray, length-1);
}
else
{
return median(rightArray, length-leftArray.size()-1);
}
}
}