package com.hzins.suanfa; /** * 归并排序 * @author Administrator * */ public class MergeSort { 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(i <= mid){ temp[k ++] = nums[i ++]; } while(j <= high){ temp[k ++] = nums[j ++]; } for (int k2 = 0; k2 < temp.length; k2++) { nums[k2 + low] = temp[k2]; } } /** * 首先,递归最底层的运算开始是两个单个元素当成子数组,所以递归的出口是left >=right * 此时递归到倒数第二层,left比right小1, 算出的mid为left,此时,出口就是mergeSort(arr, mid + 1, right) * 和mergeSort(arr, left, mid) * * @param arr * @param left * @param right */ public static void mergeSort(int[] arr, int left,int right){ if(left >= right){ return ; } int mid = (left + right) / 2; mergeSort(arr, mid + 1, right); mergeSort(arr, left, mid); merge(arr, left, mid, right); } public static void main(String[] args) { int[] a = {-1,2,-3,4,-5,6,-7,8,-9}; mergeSort(a, 0, a.length - 1); for(int i = 0;i<a.length;i++){ System.out.println(a[i] + " "); } } }