RSS

How will you find kth largest element in an array

Fri, Mar 5, 2010

Algorithm

Method1) Modified Quick sort
 
Stop processing when pivot is kth element
void q_select( int a[], const  unsigned int k, const unsigned int left,
const unsigned int right)
{
         if(left<=right)
         {
           int pivot=median3(a,left,right);
           unsigned int m=left, n=right-1;
           while(1)
           {
             while( a[++m]< pivot);
             while( a[++n]> pivot);
             if(i                swap(a[m],a[n]);
             else
               break;
           }
           swap(a[m], a[right-1]);
           if(k              q_select(a,k,left,m-1);
           else
             q_select(a,k,m+1,right);
         }
}
 
 

Method2)
 
Make a heap of k element
At the end of visiting all the element the head
will give the kth largest element
 
 

Method3)
 
Sort the element.
Get the value in the kth index

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.