1.1编写一个程序解决选择问题,令k = N/2.画出表格显示你的程序对于N为不同值的运行时间。
代码如下:
#include <iostream>
#include <time.h>
using namespace std;
int select(int A[],int k,int n){
int *minHeap = (int *)malloc(sizeof(int)*k);
int heapSize = 0;
int i,j;
minHeap[heapSize++] = A[0];
for(i = 1;i<k;i++){
for(j = heapSize;j>0;j--){
if(minHeap[j-1]<A[i])
break;
minHeap[j] = minHeap[j-1];
}
minHeap[j] = A[i];
heapSize++;
}//get K elements in array
for(i = k;i<n;i++){
if(minHeap[heapSize-1]<A[i])
continue;
//将A[i]插入其中
for(j = heapSize-1;j>0;j--){
if(minHeap[j-1]<A[i])
break;
minHeap[j] = minHeap[j-1];
}
minHeap[j] = A[i];
}
cout<<"minHeap";
for(i = 0;i<k;i++)
cout<<minHeap[i]<<" ";
cout<<endl;
return minHeap[heapSize-1];
}
int main(){
srand((unsigned)time(NULL));
int i=0;
int n = 10000;
int *A = (int *)malloc(sizeof(int)*n);
while(i<n){
A[i] = rand()%10000;
cout<<A[i++]<<" ";
}
cout<<endl;
clock_t start = clock();
cout<<"number:"<<select(A,n/2,n)<<endl;
clock_t end = clock();
cout<<"time:"<<end-start<<endl;
free(A);
system("pause");
}