- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- int partition(int arr[], int l, int r)
- {
- int x = arr[r], i = l;
- for (int j = l; j <= r - 1; j++)
- {
- if (arr[j] <= x)
- {
- swap(arr[i], arr[j]);
- i++;
- }
- }
- swap(arr[i], arr[r]);
- return i;
- }
- int GetKth(int* a, int low, int high,int k)
- {
- int pivot;
- if (low < high)
- {
- pivot = partition(a,low,high);
- if ((pivot-low + 1) == k)
- return a[pivot];
- else if ((pivot-low + 1) > k)
- return GetKth(a,low,pivot-1,k);
- else
- return GetKth(a, pivot+1,high, k);
- }
- }
- int main()
- {
- int a[]={1,4,6,7,98,23,24,56};
- int n = 8, k = 3;
- cout << GetKth(a,0,7,3);
- }
原文:http://blog.csdn.net/u014682691/article/details/51029582