Look for the number of the first K small.

Source: Internet
Author: User

Thought, the use of fast-line thinking, constantly looking for decomposition points, the demarcation point of the subscript and K-1 comparison if equal, return the value, otherwise update the left and right boundary. When the value in the left and right bounds is less than or equal to 2, the insertion sort is used to return a[k-1]

int Findcut (vector<int>& A, int l, int r) {if (L + 1 >= r) {return-1;} int pivot = A[l];int i = l, j = R;while (true) {do{i++;} while (I<r&&a[i] < pivot);d o{j--;} while (J>l& ; &a[j] >= pivot); if (i >= j) Break;int temp = a[i];a[i] = a[j];a[j] = temp;} A[L] = A[j];a[j] = Pivot;return J;} void Insert_sort (vector<int>&a, int l, int r) {for (int i = l + 1; i < R; i++) {int j=i,pivot = A[i];while (J&G T;l&&pivot < a[j-1]) {a[j] = a[j-1];j--;} A[J] = pivot;}}  int findkth (vector<int>a, int n, int K) {int left = 0, right = N;while (Left+1 < right) {int cut = Findcut (A, left, right), if (cut = = K-1) return A[cut];else if (Cut < K-1) {left = cut + 1;} Else{right = Cut;}} Insert_sort (A, left, right); return a[k-1];}

  

Look for the number of the first K small.

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.