标签:
自己写的代码,记录一下
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); } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4645412.html