从数组中找出第n大的数

基本思路就是随便找一个数,遍历数组,比这个数大的那么放到这个数的左边,比这个数小的放在这个数的右边。如果左边的数+1 == 这个n   那么当前这个数就是我们需要返回的,否则遍历左侧或者右侧的数组,条件是 如果左边的数很少,比如只有1个 ,你需要得到第3大的数,明显需要遍历右侧,否则就遍历左侧 。如此递归进行

 public static    class Util

{

          public static  int INVALID_INT_VALUE = 1 << 31;
        //nStartIndex为数组开始的索引 nArrayLength为数组的长度 k为第k大的数 
        public static int FindMaxValueN(int[] array,int nStartIndex, int nArrayLength, int k) 
        {
            if(nStartIndex < 0 || nArrayLength > array.Length || k > array.Length)
            {
                return INVALID_INT_VALUE;
            }
            int refValue = array[nStartIndex];
            int nLeftCount = 0;
            for(int i = nStartIndex; i < nStartIndex + nArrayLength; i++)
            {
                if(refValue < array[i] )
                {
                    int recordValue = array[i];
                    for(int j = i-1; j >= 0; j--)
                    {
                        array[j + 1] = array[j];
                    }
                    array[nStartIndex] = recordValue;
                    ++nLeftCount;
                }
            }
           
            if (nLeftCount == k - 1)
            {
                return array[nStartIndex + k-1];
            }
            else if (nLeftCount > k - 1)
            {
                //遍历左测 
                return FindMaxValueN(array, nStartIndex, nLeftCount, k );
            }
            else
            {
                //遍历右测 
                return FindMaxValueN(array, nStartIndex + nLeftCount + 1, nArrayLength - nLeftCount -1,k - nLeftCount - 1 );
            }
        }

}

//测试用例 

static void Main2(string[] args)
        {
            Console.WriteLine((5 << 2) & 6);
            int[] a = { 1, 2, 3, 4, 5 };
            int[] b = { 5, 4, 3, 2, 1 };
            int[] c = { 1, 5, 3, 4, 2 };
            int[] d = { 2, 3, 1, 4, 5 };
            for(int i = 0; i < 5; i++)
            {
                Console.WriteLine("-------第" + (i+1) + "大的数为");
                Console.WriteLine( Util.FindMaxValueN(a, 0, a.Length, i+1));
                Console.WriteLine(Util.FindMaxValueN(b, 0, b.Length, i+1));
                Console.WriteLine(Util.FindMaxValueN(c, 0, c.Length, i+1));
                Console.WriteLine(Util.FindMaxValueN(d, 0, d.Length, i+1));
                Console.WriteLine("-------end");
            }
            Console.ReadKey();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值