您的位置:首页 > 其它

写一段程序,找出数组中第k大小的数,输出数所在的位置。

2016-05-17 15:18 417 查看
基本上是利用排序思想,稍微改造以适应这种需求。比如最简单的冒泡排序,冒泡到第k次时就找到了这个数(需要提前缓存原始索引位置);快速排序的思想,把数组分割成大于和小于某值的两部分后,判断每部分的元素个数,然后递归分割,等等。

下面这个代码是基于快排的思想:

using System;

namespace test01
{
class Program
{
static int sortCount = 0;
static void Main(string[] args)
{
int [] array = {2,3,5,6,4,1,8};
Console.Write("数组未排序: ");
foreach (int s in array)
{
Console.Write("  " + s);
}
Console.WriteLine("");
int k = 2;
int i = FastFind(array, 0, 6, k);

Console.WriteLine("第"+k+"个大的数是: "+i);
Console.ReadKey();
}

//在start到end位置寻找第k个大的数
static int FastFind(int[] array, int start, int end, int k)
{

int arraySize = array.Length;
if (start < 0 || end >= arraySize || k > arraySize)
return -1;  //返回不合格的数字,如果数组里面有负数,需要修改

int low = start, high = end;

int bs = array[low];

while (low < high)
{
while (array[high] >= bs && high > low)
{
high--;
}
if (high > low)
{
array[low] = array[high];
low++;
}

while (array[low] <= bs && low < high)
{
low++;
}
if (low < high)
{
array[high] = array[low];
high--;
}
}
array[low] = bs;

Console.Write("第" + (++sortCount) + "次排序后:");
foreach(int s in array)
{
Console.Write("  "+s);
}
Console.WriteLine("");
int rightCount = end - low; //右侧还有几个数
if (rightCount == k - 1)  //此次排序右侧有(k-1)个数大于 bs,则bs正是第k个大的数
{
return bs;
}
else if (rightCount < k - 1) //即第k个大的数存在于左侧
{
return FastFind(array, start, low - 1, k - rightCount - 1);
}
else //右侧有很多数大于bs,即第k个大的数存在于右侧
{
return FastFind(array, low + 1, end, k);
}
}
}
}
输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: