码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序 Merge Sort

时间:2015-07-14 15:25:15      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

自己写的代码,记录一下

public class MergeSort {
//    recursive
    public static void mergeSort(int[] nums, int start, int end) {
        if(start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        mergeSort(nums, start, mid);
        mergeSort(nums, mid + 1, end);
        merge(nums, start, mid, end);
    }

    public static void merge(int[] nums, int start, int mid, int end) {
        int[] temp = new int[end - start + 1];
        int i = start, j = mid + 1, k = 0;
        while(i <= mid && j <= end) {
            if(nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j++];
            }
        }
        while(i <= mid) {
            temp[k++] = nums[i++];
        }
        while(j <= end) {
            temp[k++] = nums[j++];
        }
        i = start;
        while(i <= end) {
            nums[i] = temp[i - start];
            i++;
        }
    }

//    itervative
    public static void mergeSort(int[] nums) {
        for(int gap = 1; gap < nums.length; gap *= 2) {
            for(int start = 0; start < nums.length; start += gap * 2) {
                merge(nums, start, Math.min(start + gap - 1, nums.length - 1), Math.min(start + gap * 2 - 1, nums.length - 1));
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{13, 6, 9, 1, 19, -21, 5};
        mergeSort(nums);
        System.out.println(nums);
    }
}

 

归并排序 Merge Sort

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4645412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!