• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C语言算法之归并排序代码

OC/C/C++ 水墨上仙 2469次浏览

C语言算法之归并排序代码

一、算法实现

归并排序的时间复杂度为O(nlgn),其代码实现如下:

int merge_sort(int *array, int min, int max)  
{  
    int mid = (min+max)/2;  
  
    if(max <= min) return 0;  
  
    merge_sort(array, min, mid);  
    merge_sort(array, mid+1, max);  
  
    merge(array, min, mid, max);  
  
    return 0;  
}  

int&nbspmerge(int&nbsp*array,&nbspint&nbspmin,&nbspint&nbspmid,&nbspint&nbspmax)&nbsp&nbsp
{&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspint&nbspi=0,&nbspj=0,&nbspidx=0;&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspint&nbsplnum&nbsp=&nbspmid-min+1,&nbsprnum&nbsp=&nbspmax-mid;&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspchar&nbsp*L=NULL,&nbsp*R=NULL;&nbsp&nbsp
&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspL&nbsp=&nbspcalloc(1,&nbsplnum*sizeof(int));&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspif(NULL&nbsp==&nbspL)&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp{&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspreturn&nbsp-1;&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp}&nbsp&nbsp
&nbsp&nbsp
&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p}&nbsp&nbsp
&nbsp&nbsp&nbsp&nbsp}&nbsp&nbsp
&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspfree(L),&nbspL=NULL;&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspfree(R),&nbspR=NULL;&nbsp&nbsp
&nbsp&nbsp&nbsp&nbspreturn&nbsp&nbsp
}&nbsp&nbsp

{–二、函数调用

#define ARRAY_NUM (10)  
  
int main(int argc, void *argv[])  
{  
    int idx=0;  
    int array[ARRAY_NUM] = {0, 9, 8, 7, 6, 5, 4, 3, 2, 1};  
  
    merge_sort(array, 0, ARRAY_NUM-1);  
  
    for(idx=0; idx<ARRAY_NUM; idx++)  
    {  
        fprintf(stdout, "array[%d] = %d\n", idx, array[idx]);  
    }  
  
    return 0;  
}  


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C语言算法之归并排序代码
喜欢 (0)
加载中……