归并排序

归并排序的时间复杂度为O(nlogn)

它采用的是分治法的思想,先将序列拆分为1个个子序列,直到每个序列的长度为1,此时每个序列都是有序的;然后将两个有序的子序列合并成为一个更大的子序列,递归此过程,直到子序列的长度和原序列相同,此时排序完成,图示如下:

具体代码如下:

import java.util.Arrays;

/**
 * Created by 亮大王 on 2017/8/31.
 */
public class no2 {
    public static void main(String[] args) {
        int a[] = {49, 38, 65, 97, 76, 13, 27};
        System.out.println(Arrays.toString(a));
        no2 nn = new no2();
        nn.mergeSort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    /**
     * 二路归并
     */
    public void mergeArray(int a[], int low, int mid, int high) {
        int temp[] = new int[high - low + 1];
        int i = low;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= high) {
            if (a[i] < a[j])
                temp[k++] = a[i++];
            else
                temp[k++] = a[j++];
        }
        while (i <= mid) {
            temp[k++] = a[i++];
        }
        while (j <= high) {
            temp[k++] = a[j++];
        }
        System.arraycopy(temp, 0, a, low, temp.length);
    }

    public void mergeSort(int a[], int low, int high) {
        int mid = (high + low) / 2;
        if (low < high) {
            mergeSort(a, low, mid);
            mergeSort(a, mid + 1, high);
            mergeArray(a, low, mid, high);
        }
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值