栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

归并排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

归并排序

2——路归并排序,将序列两两分组进行排序,共有n/2组;然后再将这些组两两进行合并排序,得到n/4组,以此类推,直到只剩下一个组为止,此时这个组便是有序的。

两两分组的时候,可以用基于二分的思想进行分组。

void mergesort(int *a,int l,int r)
{
    if(l>=r)
        return;
    else
    {
        int mid=l+(r-l)/2;
        mergesort(a,l,mid);
        mergesort(a,mid+1,r);
        my_merge(a,l,mid,mid+1,r);
    }
}

归并排序
void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列,tow point :将两个有序序列合并为一个有序序列,O(n)

void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
{
    int temp[r2-l1+1],index=0,i=l1,j=l2;
    while(i<=r1&&j<=r2)
    {
        if(a[i]             temp[index++]=a[i++];
        else
            temp[index++]=a[j++];
    }

    while(i<=r1)
        temp[index++]=a[i++];
    while(j<=r2)
        temp[index++]=a[j++];
    for(i=0;i         a[l1+i]=temp[i];
}

/**
#include 
#include 
#include 
#include 
using namespace std;
void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
{
    int temp[r2-l1+1],index=0,i=l1,j=l2;
    while(i<=r1&&j<=r2)
    {
        if(a[i]=r)
        return;
    else
    {
        int mid=l+(r-l)/2;
        mergesort(a,l,mid);
        mergesort(a,mid+1,r);
        my_merge(a,l,mid,mid+1,r);
    }
}

int main()
{
    int n;
    cin >> n;
    int a[n];
    for(int i=0;i> a[i];
    mergesort(a,0,n);
    for(auto b: a)
        cout << b << ' ';
    cout << endl;

    cout << "Hello world!" << endl;
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号