堆排(二)——实现topK元素的寻找

用自己写的堆,和STL标准库中自带的堆比较
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;
}

在SLT自带的函数中  (容器的begin,容器的end后面的一位)

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/eereere/article/details/80294856
文章标签:
个人分类: c++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭