Use quick sorting to find the k-th Element

Source: Internet
Author: User

Use quick sorting to find the k-th Element

# Include
 
  
# Include
  
   
# Include
   
    
Using namespace std; // calculates the median of the first element, intermediate element, and end element, and exchanges the median with the first element. inline void medianAsPivot (int arr [], const int & left, const int & right) {const int middle = left + (right-left)> 1; const int l = arr [left]; const int m = arr [middle]; const int r = arr [right]; if (l <= m & m <= r | r <= m & m <= l) swap (arr [left], arr [middle]); if (l <= r & r <= m | m <= r & r <= l) swap (arr [left], arr [right]);} // calculates the partition position I. All elements on the left of the position are smaller than this element, all elements on the right side are not less than this element // At the same time, the element value obtained for this position is the largest I + 1 element int partition (int arr [], const int & left, const int & right) {if (left <right) {medianAsPivot (arr, left, right); int I = left; int j = right; int key = arr [I]; // use the first element as the while (I <j) {while (I
    
     
= Key) j --; if (I <j) arr [I ++] = arr [j]; while (I
     
      
N-k) {I = 0; j = position-1;} else return arr [position] ;}} int main () {int arr [] = {7, 8, 9, 1, 2, 3, 6, 5, 4}; int size = sizeof (arr)/sizeof (int); int k = 8; int kNum = findKth (arr, size, k); copy (arr, arr + size, ostream_iterator
      
        (Cout, ""); printf ("\ n"); printf ("The % dth number is % d. \ n", k, kNum); return 0 ;}
      
     
    
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.