#include <iostream>
using namespace std;
#define SIZE 10
#define K 5
void heapify(int* array, int size, int i)
{
int left = i * 2 + 1;
int right = i * 2 + 2;
int min_idx = i;
if (left < size && array[left] < array[min_idx])
min_idx = left;
if (right < size && array[right] < array[min_idx])
min_idx = right;
if (min_idx != i)
{
swap(array[i], array[min_idx]);
heapify(array, size, min_idx);
}
}
void build_heap(int* array, int size)
{
for (int i=size/2; i>=0; i--)
{
heapify(array, size, i);
}
}
void kth(int* array, int size, int k)
{
build_heap(array, k);
for (int i=k+1; i<size; i++)
{
if (array[i] > array[0])
{
swap(array[i], array[0]);
heapify(array, k, 0);
}
}
}
int main()
{
int* array = new int[SIZE];
for (int i=0; i<SIZE; i++)
array[i] = rand()%100;
for (int i=0; i<SIZE; i++)
cout << array[i] << " ";
cout << endl;
kth(array, SIZE, K);
cout << "the most max " << K << " numbers are:";
for (int i=0; i<K; i++)
cout << array[i] << " ";
cout << endl;
delete[] array;
return 1;
}
最小堆算法求Top K
最新推荐文章于 2021-03-18 19:38:36 发布