堆排序
发表于:2024-11-27 作者:热门IT资讯网编辑
编辑最后更新 2024年11月27日,#includevoid Show(int arr[], int n){ int i; for ( i=0; ia[i])//根比左右都大,跳出循环
#includevoid Show(int arr[], int n){ int i; for ( i=0; i a[i])//根比左右都大,跳出循环 break; else{ a[start] = a[i];//把孩子子树中最大的值放在父节点 start = i; } } a[start] = temp;}int* HeapBuild(int array[], int length){ int i; for ( i = length / 2 - 1; i >= 0; i--) { HeapAdjust(array, i, length); } return array;}// 堆排序算法int* HeapSort(int a[],int length){ int i; a = HeapBuild(a,length); for(i = length-1;i>0;i--){ Swap(&a[0],&a[i]); HeapAdjust(a,0,i); } return a;}int main(){ //测试数据 int *a; int arr_test[10] = { 8, 4, 2, 3, 5, 1, 6, 9, 0, 7 }; Show(arr_test,10); a = HeapSort(arr_test,10); Show(a,10); return 0;}优化:#include #include int * DuiPaixu(int a[],int n){ int end = n,i,t,x,y; while(end >= 1){ while(1){ int flag = 0; i=end/2; while(i > 0){ if(a[i] < a[2*i]){ t = a[i]; a[i] = a[2*i]; a[2*i] = t; flag = 1; } if(2*i+1 <= end&&a[i] < a[2*i+1]){ x = a[i]; a[i] = a[2*i+1]; a[2*i+1] = x; flag = 1; } i--; } if(!flag) break; } y = a[1]; a[1] = a[end]; a[end] = y; end--; } return a;}void Print(int a[],int n){ int i; for(i=1;i<=n;i++){ printf("%5d",a[i]); }}int main(void){ int n,i; int * a; printf("请输入数组长度n= "); scanf("%d",&n); a=(int*)malloc(n*sizeof(int)); printf("请输入数组元素: "); for(i=1;i<=n;i++){ scanf("%d",&a[i]); } a = DuiPaixu(a,n); Print(a,n); return 0;}