您的位置:首页 > 编程语言 > C语言/C++

迅雷四川大学(整个西南地区)C++第二轮笔试题(详解答案) ---堆排序

2010-12-18 10:29 302 查看
 

从1亿个数中,找出最大的1000个数。效率要尽可能的高,使用的额外空间要尽可能小。

void max_num(int* source_num,int* max_num)

source_num:数组包括所有的1亿个数。

max_num:保存最大的1000个数。

#注:不能使用任何库函数。

using namespace std;

/**
*调整堆,调整为最小堆(由底向上一层一层排序)
*i:需要调整元素的编号
*m:边界元素
*/
void adjust_heap(int heap[],int i,int m){
int temp,child;
temp = heap[i];
child = 2 * i;
while(child <= m){
if(child < m){//表示元素有右子树
if(heap[child] > heap[child + 1]){//选出最小的子元素
child++;
}
}
if(temp > heap[child]){
heap[i] = heap[child];
i = child;
child = 2 * i;
}else{//因为由下到上的排列,所以条件将终止
break;
}
heap[i] = temp;
}
}
/**
*堆排序
*m:排序的个数
*/
void heap_sort(int heap[],int num,int arry[],int array_len){
int i,v,temp,key = 0;
for(i = num;i > 0;i--){
heap[i] = heap[i - 1];//元素向后移动一位
}
for(i = num/2;i > 0;i--){
adjust_heap(heap,i,num);
}
//通过以上的排序,最小元素已经在下标为1的位置上了,现在只需要判断当前元素是否比下标为1的元素大
cout<<array_len<<endl;
temp = num;
while(temp < array_len){
key = arry[temp];
if(key > heap[1]){
heap[1] = key;
//调整堆
adjust_heap(heap,1,num);
}
temp++;
}

}
//
/**
*source_num:数组包括所有的1亿个数。
*max_num:保存最大的1000个数。
*/
void max_num(int* source_num,int* max_num){
heap_sort(max_num,10,source_num,26);
}
int main(){
int arry[] = {12,12,54,76,893,43,2,76,9,773,13,96,4,45,6,7,3,2,2,345,234,1,656,34,73,6843};//26个元素
int a[11] = {12,12,54,76,893,43,2,76,9,773};//10个元素
max_num(arry ,a);
int i = 1;
for(;i<11;i++){
printf("%5d",a[i]);
}
int k;
cin>>k;
return 0;
}
 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++