Select the smallest element of K

Source: Internet
Author: User

As an extended application for quick sorting, here is a question about choosing the K-min element.

1. Description of the problem

Given the n elements in a linear sequence and an integer k, 0<=k<n, it is required to find the nth element of this n element.

2. Solution method

2.1 Direct sorting

Using the quick sort and then selecting the K element, the time complexity required is O (N*LOGN).

2.2 Solving "divide-and-conquer method" with the idea of quick sorting

In the quick sort we use the partition method to find the middle element each time, can ensure that the left element is smaller than it, and the right side is larger than it. So we can take advantage of this and let us find the K element in the average time of O (n).

1 intPartitionintInt_array[],intLowintHigh )2 {3     intFirst = low, last =High ;4     intKey =Int_array[first];5 6      while(First <Last )7     {8          while(First < last && Int_array[last] >= key)--Last ;9Int_array[first] =Int_array[last];Ten          while(First < last && Int_array[first] <= key) first++; OneInt_array[last] =Int_array[first]; A     } -Int_array[first] =key; -     returnFirst ; the } -  - int Select(intA[],intLowintHighintk) - { +         intindex =partition (A, low, high); -         if(Index = =k) +             returnA[index]; A         Else  at         { -             if(K <index) -                 Select(A, low, index-1, k); -             Else -                 Select(A, index+1, High, Kindex); -         } in}

Select the smallest element of K

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.