#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);
}
寻找数组中第k大的数
最新推荐文章于 2021-06-05 00:17:34 发布