基礎演算法 分治法之合并排序

來源:互聯網
上載者:User

標籤:rand   基礎   blog   stdio.h   演算法   排序演算法   std   大小   code   

思想: 合并排序演算法的分治策略是將待排序元素分成大小大致相同的兩個子集合,分別對兩個子集合進行排序,最終將排好序的子集合合并成所要求的排好序的集合。

 

 1 #include <stdio.h>   2     3 void merge(int a[],int p,int q,int r)   4 {   5     int n1=q-p+1,n2=r-q;   6     int b1[n1];   7     int b2[n2];   8     int i=0,j=0,temp1=p,temp2=q;   9     while(p<=q)  10     {  11         b1[i]=a[p];  12         ++i;  13         ++p;  14     }  15     while(q+1<=r)  16     {  17         b2[j]=a[q+1];  18         ++j;  19         ++q;  20     }  21    22     p=temp1;q=temp2;  23     i=0,j=0;  24     while(p<=r)  25     {  26         if(i==n1)           27         {  28             a[p]=b2[j];  29             ++j;  30         }  31         else if(j==n2)  32         {  33             a[p]=b1[i];  34             ++i;  35         }  36        37         else if(b1[i]<b2[j])  38         {  39             a[p]=b1[i];  40             ++i;  41         }  42         else  43         {  44             a[p]=b2[j];  45             ++j;  46         }  47         ++p;  48     }  49 }  50    51 void merge_sort(int a[],int p,int r)  52 {  53     int q=0;  54     if(p<r)  55     {  56         q=(p+r)/2;  57         merge_sort(a,p,q);   58         merge_sort(a,q+1,r);  59         merge(a,p,q,r);  60     }  61 }  62    63 int main()  64 {  65     int i, a[100];  66     srand(time(0));  67     for ( i = 1; i < 101; ++i ){  68         a[i-1] = rand() % 1001;  69         printf( "%3d ", a[i-1] );  70         if(i%15==0) printf("\n");   71     }  72     printf("\n\n");  73     SelectionSort(a, 100);  74     for ( i = 1; i < 101; ++i ){  75         printf( "%3d ", a[i-1] );  76         if(i%15==0) printf("\n");   77     }  78     getch();  79     return 0;  80 }  

 

基礎演算法 分治法之合并排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.