如果寻找给定的数组中第几大的数,采用前面的方法就不现实,因为我们不可能定义几个变量来存放,并且也不现实,这时我们当然想到了数组,而且是有序数组,按照从大到小的方式进行排序,再套用前面的逻辑就可以了.


internal static int FindIndexMaximum(int[] input, int index)
{
if (input == null || input.Length < index)
{
throw new InvalidOperationException("the input paramter is invalid, please check your input");
}
//Get the sorted array
int[] sorted = new int[index];
int k = 0;
for (int i = 0; i < index; i++)
{
k = i;
while (k > 0 && input[i] > sorted[k - 1])
{
sorted[k] = sorted[k - 1];
k--;
}
sorted[k] = input[i];
}
//Compare the number one by one.
for (int i = index; i < input.Length; i++)
{
k = index;
while (k > 0 && input[i] > sorted[k - 1])
{
if (k != index)
{
sorted[k] = sorted[k - 1];
}
k--;
}
if (input[i] > sorted[index - 1])
{
sorted[k] = input[i];
}
}
return sorted[index - 1];
}
{
if (input == null || input.Length < index)
{
throw new InvalidOperationException("the input paramter is invalid, please check your input");
}
//Get the sorted array
int[] sorted = new int[index];
int k = 0;
for (int i = 0; i < index; i++)
{
k = i;
while (k > 0 && input[i] > sorted[k - 1])
{
sorted[k] = sorted[k - 1];
k--;
}
sorted[k] = input[i];
}
//Compare the number one by one.
for (int i = index; i < input.Length; i++)
{
k = index;
while (k > 0 && input[i] > sorted[k - 1])
{
if (k != index)
{
sorted[k] = sorted[k - 1];
}
k--;
}
if (input[i] > sorted[index - 1])
{
sorted[k] = input[i];
}
}
return sorted[index - 1];
}
其实这里主要是使用了两次插入式排序方式,第一次是用来初始化临时数组,并保存其有序.第二次就是从原始数组的index位置开始取数,一个一个地与临时数组的最小值进行比较,如果小于最小值就跳过,如果大于,则一一比较,并插入到合适的位置.这样临时数组的最后一个(?)就是你要找的数字. 这儿还是有一个问题在这儿,如果前面的数字有重复的,那这儿就会有问题?如果让你来改进,你会如何做呢?
另外,让你来设计它的测试用例,你会给出哪些呢? 如果你有不错的想法,请与大家分享.