寻找数组中第k大的数

#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);


}

posted @ 2016-03-31 19:54  牧羊少年10号  阅读(133)  评论(0编辑  收藏  举报