Algorithm backup ---- Find the kth largest number(寻找第K大数)

  Here is a way to find the k-th largest number from an ayyay based on the theory of quick sort with an algorithmic complexity of O(n).

  First we find a base element from the array randomly, and then reorder the list so that all elements which are greater than the pivot come before the pivot (Spart) and all elements less than the pivot come after it(Sb part). Now we get two cases:

  1. Element number of Sa part is smaller than K, So the answer is the (k-|Sa|)-th number in Sb;

  2. If |Sa|>=K, so return the K-th largest number of Sa.

  Below is the implementation:

///   <summary>
///  Patition according to quick sort algrithm
///   </summary>
///   <param name="numbers"> numbers array to be parted </param>
///   <param name="begin"> start subscript </param>
///   <param name="end"> end subscript </param>
///   <returns> partition point </returns>
public   static   int  Partition( int [] numbers,  int  begin,  int  end)
{
    
int  key  =  numbers[begin];
    
while (begin  <  end)
    {
        
while (begin  <  end  &&  key  >=  numbers[end])
            end
-- ;
        
if  (begin  <  end) 
            numbers[begin] 
=  numbers[end];
        
while (begin  <  end  &&  key  <=  numbers[begin])
            begin
++ ;
        
if  (begin  <  end)
            numbers[end] 
=  numbers[begin];
    }
    numbers[begin] 
=  key;    
    
return  begin;
}

///   <summary>
///  Get the k-th largest number from an unsorted array
///   </summary>
///   <param name="numbers"> numbers array </param>
///   <param name="begin"> start subscript </param>
///   <param name="end"> end subscript </param>
///   <param name="k"> Point which number to find </param>
///   <returns> the k-th largest number </returns>
public   static   int  GetNumber( int [] numbers,  int  begin,  int  end,  int  k)
{
    
// Find the partition according to quick-sort algorithm.
     int  n  =  Partition(numbers, begin, end);
    
    
if  (n  +   1   ==  k)
    {
        
return  numbers[n];
    }
    
else   if  (n  +   1   <  k)
    {
        
return  GetNumber(numbers, n  +   1 , end, k);
    }
    
else
    {
        
return  GetNumber(numbers, begin, n  -   1 , k);
    }
}

 

Go to my home page for more posts

转载于:https://www.cnblogs.com/lantionzy/archive/2009/11/03/1595213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值