前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c-归并排序

c-归并排序

作者头像
kdyonly
发布2023-03-03 19:18:44
3170
发布2023-03-03 19:18:44
举报
文章被收录于专栏:个人编程笔记个人编程笔记

浏览量 5

归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

简单的说来归并排序算法,就是相当于将一个数组分为两个有序数列,然后再将其有序合并起来,当然这是指的最后一步,那么如何得到这两个序列呢,又可以将两个序列各自在分成两个序列,最后你发现一个数做为一个序列了,这不就是典型的递归么?理解上面应该不难,那么还是得靠自己想清楚。以下代码参考了白话经典算法,上次给大家发的pdf。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
//合并两个序列
void mergearray(int a[],int first,int mid,int last,int temp[])
{
    int i=first,j=mid+1;
    int m=mid,n=last;
    int k=0;
while(i<=m&&j<=n)
{
    if(a[i]<a[j])
        temp[k++]=a[i++];
    else
        temp[k++]=a[j++];
}
while(i<=m)
{
    temp[k++]=a[i++];
}
while(j<=n)
{
    temp[k++]=a[j++];
}
for(i=0;i<k;i++)
    a[first+i]=temp[i];
}
void mergesort(int a[],int first,int last,int temp[])
{
    if(first<last)
    {
        int mid=(first+last)/2;
        mergesort(a,first,mid,temp);//左边有序
        mergesort(a,mid+1,last,temp);//右边有序
        mergearray(a,first,mid,last,temp);
    }
}
void main()
{
    int temp[10]={0};
    int a[10]={2,6,8,4,1,3,7,9,5,0};
    mergesort(a,0,10-1,temp);
    for(int i=0;i<10;i++)
    {
        printf("%d",a[i]);
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-11-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档