我有这段代码,可以找到一个无序数组中第k个最小的元素。我想知道什么需要更改,以便它可以找到数组中第K个最大的元素。例如,如果我放2,它将在数组中找到第二大元素
public static double FindTheKSmallest(double[] tab, int find)
{
//the method is searching for the k-th SMALLEST element in the array and returns the result as tab[k]: smallest element (find=1) is tab[0], second smallest (isci=2) is tab[1]...
int k = find - 1;
if (tab == null || tab.Length <= k)
throw new Exception("This table doesn't exist or has incorrect parameters");
int fromWhere = 0, toEnd = tab.Length - 1;
while (fromWhere < toEnd)
{
int leftBorder = fromWhere;
int rightBorder = toEnd;
double Middle = tab[(leftBorder + rightBorder) / 2];
// We repeat until the left and right border meet
while (leftBorder < rightBorder)
{
if (tab[leftBorder] >= Middle)
{
// We move the bigger numbers to the right border
double tmp = tab[rightBorder];
tab[rightBorder] = tab[leftBorder];
tab[leftBorder] = tmp;
rightBorder--;
}
else
{
//value is smaller than the pivot, so we ignore it
leftBorder++;
}
}
// if we went through the middle, we go one step back
if (tab[leftBorder] > Middle)
leftBorder--;
//indeks leftBorder is at the end of the first k elements
if (k <= leftBorder)
{
toEnd = leftBorder;
}
else
{
fromWhere = leftBorder + 1;
}
}
return tab[k];
}
static void Main(string[] args)
{
double[] tab = { 3, 5, 8, 1, 9, 6, 5 };
Console.WriteLine(FindTheKSmallest(tab, 2)); //it should be 8
Console.ReadKey();
}