Home | Web Board | ProblemSet | Standing | Status | Statistics |
请分别应用堆排序方法(大顶堆)和归并排序方法实现一组非常大的数据的递增排序,分别输出每次堆整序之后对应的堆顶的值和每次归并之后的局部序列。(考查堆排序算法和归并排序算法)
第一行输入为n(0 <= n <= 10000)为n个要排序的数字;
接下来输入一行,包括n个要排序的数字,保证所有的数字都在int范围内。
前n行每行输出一次堆整序后堆顶的值(初建堆的堆顶元素在第一个输出,之后n - 1行每行输出一次堆整序后堆顶元素的值)。
接下来输出每一次归并后的局部序列,具体内容见输出样例。
#include<iostream> #include<cstring> #include<cstdio> #include<string.h> #include<algorithm> #define maxsize 10005 using namespace std; static int H[maxsize],M[maxsize],c[maxsize],num[maxsize]; void HeapAdjust(int List[],int s,int m); void HeapSort(int List[],int n); void HeapAdjust(int List[],int s,int m) { int r=List[s]; int i=2*s; while(i<=m) { if(i<m&&List[i]<List[i+1]) { ++i; } if(r>=List[i]) { break; } List[s]=List[i]; s=i; i*=2; } List[s]=r; } void CreatHeap(int List[],int n) { int i=n/2; while(i!=0) { HeapAdjust(List,i,n); i--; } } void Msort(int array[],int l,int h) { if(l!=h) { int m=(l+h)/2; int f=l; int F=m+1; int s=h; Msort(array,f,m); Msort(array,m+1,s); int k=l; int ans=f; int Ans=F; while(ans<=m&&Ans<=s) { if(array[ans]<array[Ans]) { num[k++]=array[ans++]; } else { num[k++]=array[Ans++]; } } while(ans<=m) { num[k++]=array[ans++]; } while(Ans<=s) { num[k++]=array[Ans++]; } int x=l; while(x<=h) { array[x]=num[x]; x++; } } int y=l; printf("[%d, %d]:",l+1,h+1); while(y<=h) { printf(" %d",array[y]); y++; } cout<<endl; } int main() { int n; while(scanf("%d",&n)!=EOF) { for(int i=0; i<n; i++) { scanf("%d",&H[i]); M[i]=H[i]; } int i=n/2; while(i>=0) { HeapAdjust(H,i,n); i--; } printf("%d\n",H[0]); int j=n-1; while(j>=1) { int temp=H[0]; H[0]=H[j]; H[j]=temp; HeapAdjust(H,0,j-1); printf("%d\n",H[0]); j--; } Msort(M,0,n-1); } return 0; }