归并排序(Merge sort)是建立在归并操作上的一种有效的排序算法。 归并操作的过程如下: 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列设定两个指针,最初位置分别为两个已经排序序列的起始位置比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置重复步骤3直到某一指针达到序列尾将另一序列剩下的所有元素直接复制到合并序列尾 最差时间复杂度最优时间复杂度平均时间复杂度最差空间复杂度 算法稳定性:稳定的。 package com.kvmk.sort; public class MergeSort { public static int[] originalArray; public static int[] helper; public static void mergeSort() { helper = new int[originalArray.length]; divide(0,originalArray.length-1); } public static void divide(int low, int high) { if (low < high) { int middle = (low +high)/2; divide(low,middle); divide(middle+1,high); combine(low,middle,high); } } public static void combine(int low, int middle, int high) { // Copy both parts into the helper array for (int i = low; i <= high ; i++) { helper[i] = originalArray[i]; } int i = low; int j = middle +1; int index = low; // Copy the smallest values from either the left or the right side back // to the original array while (i <= middle && j <= high) { if (helper[i] <= helper[j]) { originalArray[index] = helper[i]; i++; } else { originalArray[index] = helper[j]; j++; } index ++; } // Copy the rest of the left side of the array into the target array while (i<=middle) { originalArray[index] = helper[i]; i++; index ++; } /*while (j<=high) { originalArray[index] = sortedArray[j]; j++; index++; }*/ } public static void printlnArray(int[] inputs) { for (int input : inputs) { System.out.println(input); } } public static void main(String[] args) { originalArray = new int[] {2,34,5,9,3,77,88,99}; mergeSort(); printlnArray(originalArray); } }