堆排序演算法

來源:互聯網
上載者:User

標籤:array   設計   左右子樹   儲存   scan   log   sift   利用   open   

 1 /* 2 請設計篩選函數void sift(int a[],int k,int n),對a[k] 進行篩選, 3 並利用其設計堆排序演算法函數void heapSort(int a[],int n), 4 對a[1]..a[n]進行升序排序。並測試在不同資料規模下的排序效率。(詳見lab10_05.c) 5 */ 6 #include "Arrayio.h" 7 #define N 10000     /*N為資料量大小,因data1.txt中只有50萬個數,所以自行設定N值時需讓N<=500000*/ 8  9 /*請將本函數補充完整,並進行測試*/10 void sift(int a[],int k,int n)11 {12       int i,j,finished;13       i=k;j=2*i;14       a[0]=a[k];15       finished=0;16       while((j<=n)&&(!finished))17       {18         if((j<n)&&(a[j+1]>a[j]))         //判斷左右子樹誰的值更大19              j++;20         if(a[0]>=a[j])21              finished=1;22         else23         {24           a[i]=a[j];25           i=j;j=2*j;26         }27       }28       a[i]=a[0];29     }30 31 void heapSort(int a[],int n)32 {33     int i;34     for (i=n/2;i>=1;i--)35         sift(a,i,n);36     for (i=n;i>1;i--)                   //當輸出根結點後,重新調整剩餘的關鍵字序列為一個新的大頂堆37         {38             a[0]=a[i];39             a[i]=a[1];40             a[1]=a[0];41             sift(a,1,i-1);42         }43 }44 45 int  main()46 {47   int a[N+1],n,i;                     /*資料存放區在a[1]...a[N]中*/48   printf("資料初始化...\n");49   n=readData(a,N,"data1.txt");      /*從data1.txt中讀入N個整數存入數組a,n為實際讀入的資料個數*/50   printf("%d個資料排序中...\n",n);51   heapSort(a,n);52   saveData(a,n,"out.txt");          /*排序結果存放在out.txt檔案中*/53   printf("排序結束,排序結果儲存在out.txt檔案中。\n");54   return 0;55 }

 

 1 #include <stdio.h> 2 #define MAX 500000 3  4 /*從檔案中讀入資料存入數組a*/ 5 int readData(int a[], int n,char *f)  /*函數返回成功讀入的資料個數*/ 6 { 7     FILE *fp; 8     int i; 9     fp=fopen(f,"r");10     if (fp==NULL)   return 0;11     else12     {13         for (i=1;i<=n && !feof(fp);i++)14             fscanf(fp,"%d",&a[i]);15         fclose(fp);16         return i-1;17     }18 }19 20 /*存檔函數*/21 void saveData(int a[],int n, char *f)22 {23     FILE *fp;24     int i;25     fp=fopen(f,"w");26     if (fp==NULL)   printf("檔案建立失敗!");27     else28     {29         for (i=1;i<=n;i++)30             {31                 fprintf(fp,"%7d",a[i]);32                 if (i%10==0) fprintf(fp,"%c",‘\n‘);33             }34         fclose(fp);35     }36 }37 38 /*輸出長度為n的整型數組*/39 void output(int a[],int n)40 {  int i;41    printf("\n數組的內容是:\n");42    for (i=1;i<=n;i++)43      {44        printf("%7d",a[i]);45        if (i%10==0) printf("\n");46      }47   printf("\n");48 }

 

堆排序演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.