#pragma #include<iostream> #include<time.h> #include<vector> using namespace std; //从十万个数中找出最大的前K个,用小堆 #define N 100000 #define K 100 vector<int> Data; //产生海量数据 void GetData() { srand(unsigned(time(0))); for (int i = 0; i < N; ++i) { Data.push_back(rand() % N + 1);//产生随机数在1到length间 } } void AdjustDown(int a[], int size, int parIndex) { int chiIndex = parIndex*2+1; while (chiIndex < size) { if (chiIndex + 1 < size&&a[chiIndex + 1] < a[chiIndex]) ++chiIndex; if (a[chiIndex] < a[parIndex]) { swap(a[chiIndex], a[parIndex]); parIndex = chiIndex; chiIndex = parIndex * 2 + 1; } else break; } } void GetTopK(vector<int>& Data) { int heapArray[K]; for (int i = 0; i < K; ++i) { heapArray[i] = Data[i]; } //调整此堆为小堆 for (int i = (K - 1 - 1) / 2; i >= 0; --i) { AdjustDown(heapArray, K, i); } for (int i = K-1; i < N; ++i) { if (heapArray[0] < Data[i]) { heapArray[0] = Data[i]; AdjustDown(heapArray, K, 0); } } } void Test1() { GetData(); GetTopK(Data); }
时间: 2024-12-28 01:24:21