归并法排序 采用二维数组直接拆分一维数组

/*
归并排序
*/



public class Sort {

    //将两个有序数组合并成一个有序数组
    public int[] guibing(int left[], int right[]) {
        int temp[] = new int[left.length + right.length];
        int t = 0;
        int i = 0;
        int j = 0;
        while (i < left.length && j < right.length) {
            if (left[i] < right[j]) {
                temp[t] = left[i];
                i++;
            } else {
                temp[t] = right[j];
                j++;
            }
            t++;
        }
        while (i >= left.length && t < temp.length) {
            temp[t] = right[j];
            j++;
            t++;
        }
        while (j >= right.length && t < temp.length) {
            temp[t] = left[i];
            i++;
            t++;
        }
        return temp;
    }
    
    //归并排序
    //给一个数组返回一个有序数组
    public int[] sort(int arr[]) {
        int[][] b = new int[arr.length][];        //利用二维数组拆分一维数组
        int i = 0;
        for (i = 0; i < arr.length; i++) {
            b[i] = new int[]{arr[i]};
        }
        //调用归并
        int recive[] = b[0];
        for (int j = 1; j < arr.length; j++) {
            recive = guibing(recive, b[j]);		//循环接收
        }
        return recive;
    }
    
    public static void main(String[] args) {
        int arr[] = {23, 56, 80, 72, 86, 96, 97};
        Sort sort = new Sort();
        int[] temp = sort.sort(arr);
        for (int i = 0; i < temp.length; i++) {
            System.out.print(temp[i] + ",");
        }
    }
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值