归并排序的使用
2016-03-31 15:49
246 查看
不多说 先上模板
#include<stdio.h>
void carry(int a[],int first,int mid,int last,int temp[])//将两个有序的数组合并
{
int i=first,j=mid,m=mid+1,n=last,k=0;
while(i<=j&&m<=n)// 比较两个数组的第一位 将较小的数放入temp 直到一个数组遍历结束
{
if(a[i]<a[m])
temp[k++]=a[i++];
else temp[k++]=a[m++];
}
while(i<=j) temp[k++]=a[i++];
while(m<=n) temp[k++]=a[m++];
for(i=0;i<k;i++)
{
a[first++]=temp[i];// 将排序好的数组放回 a
}
}
void sort(int a[],int first,int last,int temp[])// 不断的将数组二分直到数组的长度为1 然后依次有序合并(有点像二叉树原理)
{
int mid;
if(first<last)// 长度为一的时候结束
{
mid=(first+last)/2;
sort(a,first,mid,temp);
sort(a,mid+1,last,temp);// 不断二分
carry(a,first,mid,last,temp); //将分好的两个数组有序合并
}
}
int main()
{
int a[10]={0,7,1,2,9,5,4,6,8,3},temp[12],i;
sort(a,1,9,temp);
for(i=1;i<=9;i++) printf("%d",a[i]);
return 0;
}
#include<stdio.h>
void carry(int a[],int first,int mid,int last,int temp[])//将两个有序的数组合并
{
int i=first,j=mid,m=mid+1,n=last,k=0;
while(i<=j&&m<=n)// 比较两个数组的第一位 将较小的数放入temp 直到一个数组遍历结束
{
if(a[i]<a[m])
temp[k++]=a[i++];
else temp[k++]=a[m++];
}
while(i<=j) temp[k++]=a[i++];
while(m<=n) temp[k++]=a[m++];
for(i=0;i<k;i++)
{
a[first++]=temp[i];// 将排序好的数组放回 a
}
}
void sort(int a[],int first,int last,int temp[])// 不断的将数组二分直到数组的长度为1 然后依次有序合并(有点像二叉树原理)
{
int mid;
if(first<last)// 长度为一的时候结束
{
mid=(first+last)/2;
sort(a,first,mid,temp);
sort(a,mid+1,last,temp);// 不断二分
carry(a,first,mid,last,temp); //将分好的两个数组有序合并
}
}
int main()
{
int a[10]={0,7,1,2,9,5,4,6,8,3},temp[12],i;
sort(a,1,9,temp);
for(i=1;i<=9;i++) printf("%d",a[i]);
return 0;
}
相关文章推荐
- IOS折线统计图
- 李彦宏:数据技术共享与“圈子联合文化”
- ExecutorService的几种关闭线程池方法
- ssh 无密码登陆
- SecurCRT命令回显设置
- 详解JavaScript表单验证(E-mail 验证)
- linux 安装svn服务端
- Linux修改内核使得普通用户可以打印kmsg内容
- 花指令
- springMVC 上传文件
- 火狐浏览器sqlite插件
- 压缩包里面excel 导出 (跨行跨列)
- 网络爬虫-URL去重
- iOS 地图定位
- Loading a 3D scene with libGDX
- 分类、标注与回归
- Fragment 监听返回键
- 几何变换详解
- For UPDATE 语句
- 在DLL中获取自身的路径