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

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

2963次浏览

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

```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
&nbsp&nbsp&nbsp&nbspR&nbsp=&nbspcalloc(1,&nb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&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;
}
```

• 版权声明

本站的文章和资源来自互联网或者站长
的原创，按照 CC BY -NC -SA 3.0 CN
协议发布和共享，转载或引用本站文章
应遵循相同协议。如果有侵犯版权的资
源请尽快联系站长，我们会在24h内删
除有争议的资源。
• 合作网站

• 友情链接

• 关于我们

一群热爱思考，热爱生活，有理想的新社会主义接班人的多维思维学习平台，天行健，君子以自强不息。地势坤，君子以厚德载物。