java_归并排序

package first;
//归并排序
public class MergeSort {
    //产生随机数组的方法
    public static int[] getarray() {
        int[] nums = new int[10];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = (int) (Math.random()*100);
        }
        return nums;
        }
    //归并方法
    public static int[] Sort(int[] nums, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            Sort(nums, low, mid);// 左边
            Sort(nums, mid + 1, high);// 右边
            Merge(nums, low, mid, high);//左右归并
        }
        return nums;
    }
    //排序方法
    public static void Merge(int[] nums, 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 (nums[i] < nums[j])
                temp[k++] = nums[i++];
            else
                temp[k++] = nums[j++];
        }
        //把右边剩余的数移到数组中
        while(j<=high)
            temp[k++] = nums[j++];
        //把左边剩余的数移到数组中
        while(i<=mid)
            temp[k++] = nums[i++];
        //把新数组中的数覆盖原数组
        for(int m=0;m < temp.length;m++)
            nums[m+low] = temp[m];
    }
    public static void main (String args[]) {
        int nums[]=getarray();
        System.out.println("随机数组为:");
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]+"  ");
        }
        Sort(nums, 0, nums.length-1);
        System.out.println("排序后:");
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i]+"  ");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值