归并排序

归并排序


算法思想:假设初始序列含有n个记录,首先将这n个记录看成n个有序的子序列,每个子序列的长度为1,然后凉凉合并,得到[n/2]个长度为2的有序子序列。
在次基础上,在对长度为2的有序子序列进行两两归并,得到若干个长度为4的有序子序列。如此重复,知道得到一个长度为n的有序序列为止。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package paixu;

import java.util.Arrays;

public class PaiXu {

    public static void main(String[] args) {
        int []a={48,62,35,77,55,14,35,98,0};
        Msort(a,0,a.length-1);
        System.out.println(Arrays.toString(a));
    }
    //使用递归的方法可实现排序
    public static void Msort(int[] a,int low,int high){  
        int mid=(low+high)/2;
        if(low<high){
        Msort(a,low,mid);
        Msort(a,mid+1,high);
        Merge(a,low,mid,high);
        }
    }
    public static void Merge(int[] a,int low,int mid,int high) {
        int []temp=new int[high-low+1];//临时变量,存放排好序的数组
        int i=low;
        int j=mid+1;
        int index=0;
        while(i<=mid&&j<=high){
            if(a[i]<=a[j]){
                temp[index]=a[i];
                i++;
            }
            else{
                temp[index]=a[j];
                j++;
            }
            index++;
        }
        while(j<=high){   //前面的序列都已排完序,而后面的序列还有剩下的元素
            temp[index]=a[j];
            index++;
            j++;
        }
        while(i<=mid){  //后面的序列都已排完序而前面的序列还有剩下的元素
            temp[index]=a[i];
            index++;
            i++;
        }
        for(int k=0;k<temp.length;k++){ //将临时数组中的元素放入a数组中
            a[k+low]=temp[k];
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值