java_归并排序

来源:互联网 发布:社会网络分析大数据 编辑:程序博客网 时间:2024/06/18 17:08
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]+"  ");        }    }}
原创粉丝点击