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 ;}