寻找最小的k个数___堆排序
在一场笔试中,碰到的题目,给一个数组,找出最小的K个数,当然首先想到的就是排序了,库函数sort一下,直接输出.
可以肯定的是这肯定不是出题者想看到的答案,各种排序算法中堆排序对这种寻找最大最小的K个数效率应该是最高的.
可惜的是笔试现场没能一挥而就...之后在电脑上实现了一下,完全的堆排序,对于寻找K个最大最小的只需用大根堆,小根堆然后判断一下到第K个就可以停止了.
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <iomanip>
#include<windows.h>
using namespace std;
static int heapsize;
void maxheap(int a[],int i)
{
//adapt down
int leftchild=2*i;
int rightchild=2*i+1;
int largest=-1;
if(leftchild<=heapsize&&a[i]<a[leftchild])
largest=leftchild;
else
largest=i;
if(rightchild<=heapsize&&a[largest]<a[rightchild])
largest=rightchild;
if(largest!=i)
{
swap(a[i],a[largest]);
maxheap(a,largest);
}
}
void buildheap(int a[])
{
// build-heap
for(int i=heapsize/2; i>=1; --i)
{
maxheap(a,i);
}
}
void heapsort()
{
int a[21];
//Seed the random-number generator with current time
srand(time(NULL));
for(int i=1; i<=20; ++i)
{
a[i]= rand()%99;
}
//build the MAX-HEAP
buildheap(a);
//do sort
for(int i=20; i>=2; --i)
{
//swap the largest and the last
swap(a[i],a[1]);
//Remove the largest
heapsize--;
//adapt from a[1]
maxheap(a,1);
}
for(int i=1; i<=20; ++i)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int k=10;
while(k>0)
{
heapsize=20;
heapsort();
--k;
//Wait 1s is to ensure that to produce time-based random number
Sleep(1000);
}
return 0;
}
结果: