Calculate the k-th number by using the Random Pseudo-fast sorting method

Source: Internet
Author: User
Divide and conquer the law to find the k-th number

The idea of "Quick Sort" is used to find the k-th large number of a series. The second year of high school started to write fast sort, but he has never been very clear about it. He knows that it is "divide", but does not understand the details. Today, with the help of this opportunity, I read the four fast-coding methods in programming Pearl River, which makes it clearer. This time, the quick ranking actually has a number. The number on the left is smaller than him, and the number on the right is bigger than him.

/*************************************** ********************************* // Randomize pseudo-fast sorting calculate the k-th number *//********************************* ***************************************/ # include <cstdio> # include <cstring> # include <algorithm> # include <cstdlib> using namespace STD; # define maxn 10100int num [maxn]; int qsort (int l, int R, int key) {int mid, LL = L, RR = R + 1; Mid = rand () % (R-l + 1) + L; swap (Num [L], num [Mi D]); While (LL <= RR) {do {ll ++;} while (LL <= R & num [ll] <num [l]); do {rr --;} while (Num [RR]> num [l]); If (LL <RR) {swap (Num [ll], num [RR]) ;}} swap (Num [L], num [RR]); If (RR-L + 1> = key) {If (RR-L + 1 = Key) return num [RR]; return qsort (L, RR, key);} else {return qsort (RR + 1, R, key-(RR-L + 1) ;}int main () {int N; while (~ Scanf ("% d", & N) {for (INT I = 0; I <n; ++ I) {scanf ("% d ", & num [I]);} int ans = qsort (0, n-1, n/2 + 1); printf ("% d \ n", ANS );} 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.