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

基本上是利用排序思想,稍微改造以适应这种需求。比如最简单的冒泡排序,冒泡到第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);
            } 
        }
    }
}
输出:



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值