排序算法之归并算法

排序算法之归并算法

算法描述;

归并排序是建立在归并操作上的一种有效算法,该算法是采用分治法,将有序的子序列合并,得到完全有序的序列,即先使每个子序列有序,在使子序列段间有序,将两个有序表合并称为2路归并

算法思路;

首先把长度为n的输入序列分为两个长度为n/2的子序列;

对两个子序列分别采用归并排序;

将两个排序好的子序列合并成一个最终的排序序列.

代码实现;

public class MergeSort{
    public static void main(String[] args){
        int[] a={12,2,19,96,98,19,3,12,7,45,64};
        sort(a);
        for(int s: a){
            System.out.println(s);
        }
    }
    public static void sort(int[] a){
        int[] temp=new int[a.length];
        sort(a,0,a.length-1,temp);
        System.out.println("执行第一个sort");

    }
    public static void sort(int[] a,int left,int right,int[] temp){
        System.out.println("执行第er个sort");
        if(left<right){
            int mid=(left+right)/2;
            sort(a,left,mid,temp);
            sort(a,mid+1,right,temp);
            merge(a,left,mid,right,temp);
        }
    }
    public static void merge(int[] a,int left,int mid,int right,int[] temp){
        int l=left;
        int r=mid+1;
        int t=0;
        while(l<=mid&&r<=right){
            if(a[l]<=a[r]){
                temp[t++]=a[l++];
            }else{
                temp[t++]=a[r++];
            }

        }
        while(l<=mid){
            temp[t++]=a[l++];
        }
        while(r<=right){
            temp[t++]=a[r++];
        }
        t=0;
        while(left<=right){
            a[left++] = temp[t++];
        }



    }
}

算法分析

归并排序是一种稳定的排序方法,和选择排序一样,归并排序并不受输入数据的影响,但表现比选择排序好得多,时间复杂度为哦(nlogn)的时间复杂度,代价是需要额外的内存空间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值