分治法之合并排序(C实现)
2015-11-04 13:43
141 查看
#include <stdio.h> void merge(int a[],int p,int q,int r) { int n1=q-p+1,n2=r-q; int b1[n1]; int b2[n2]; int i=0,j=0,temp1=p,temp2=q; while(p<=q) { b1[i]=a[p]; ++i; ++p; } while(q+1<=r) { b2[j]=a[q+1]; ++j; ++q; } p=temp1;q=temp2; i=0,j=0; while(p<=r) { if(i==n1) { a[p]=b2[j]; ++j; } else if(j==n2) { a[p]=b1[i]; ++i; } else if(b1[i]<b2[j]) { a[p]=b1[i]; ++i; } else { a[p]=b2[j]; ++j; } ++p; } } void merge_sort(int a[],int p,int r) { int q=0; if(p<r) { q=(p+r)/2; merge_sort(a,p,q); merge_sort(a,q+1,r); merge(a,p,q,r); } } int main() { int i, a[100]; srand(time(0)); for ( i = 1; i < 101; ++i ){ a[i-1] = rand() % 1001; printf( "%3d ", a[i-1] ); if(i%15==0) printf("\n"); } printf("\n\n"); SelectionSort(a, 100); for ( i = 1; i < 101; ++i ){ printf( "%3d ", a[i-1] ); if(i%15==0) printf("\n"); } getch(); return 0; }
运行效果图
相关文章推荐
- jquery rotate
- 解决Delphi开发DLL中窗体按钮显示状态不刷新问题.
- Android入门---ImageView(图像视图)
- net-snmp配置文件snmp.conf
- Python3 官方文档翻译 - 4.7 函数定义
- C#占位符和格式化字符串
- HDU 3068 最长回文 Manacher
- 从”JAVA“而终 12:java集合框架API讲解
- ReactionCocoa 登陆界面
- PHP:错误 Deprecated: Function split() is deprecated in ... 解决办法
- Docker
- MySQL事务autocommit自动提交
- 最快遍历完图中重要节点 树的直径 Codeforces 328 (Div. 2) D. Super M
- Android Platform Version 和 API Level对照
- 缓存应用--Memcached分布式缓存简介
- 网站计数器的设计
- spring mvc 图形验证码
- 数据库SQL中Like的用法总结
- exp/imp expdp/impdp乱码
- hdu 5532(最长上升子序列)