# 堆排（二）——实现topK元素的寻找

int findTopK1(int* arr, int n, int k)
{
MaxHeap<int> mapheap = MaxHeap<int>(arr, n);
//mapheap.testPrint();

for (int i = 1; i <=k-1; i++)
{
cout<<"the "<<i<<"top is:"<<mapheap.extractMax()<<endl;
}

return mapheap.extractMax();

}

int findTopK2(int *arr, int n, int k)
{
make_heap(arr, arr + n );
//cout << "初始的堆顶" << arr[0] << endl;
for (int i = 1; i <= k-1; i++)
{
cout << "the " << i << "top is:" << arr[0] << endl;
pop_heap(arr, arr + n - 1);
n--;
}
/*sort_heap(arr, arr + n );
for (int i = 0; i <n; i++)
cout << arr[i] << " ";
cout << endl;*/
return arr[0];
}

int main()
{
int n = 1000000;
int k = 8;
int *arr = SortTestHelper::generateRandomArray(n, 0, n);
//SortTestHelper::printArray(arr, n);

cout << "在" << n <<"个元素中，寻找第" <<k<<"大元素" << endl;

time_t startTime = clock();
int res1 = findTopK1(arr, n, k);
time_t endTime = clock();
cout <<"方法一的topK是"<< res1<<"用时" << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;

startTime = clock();
int res2 = findTopK2(arr, n, k);
endTime = clock();

cout <<"方法二的topK是"<< res2<< "用时" << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;

return 0;
}