``````import java.util.Arrays;

public class Algorithm {

public static void main(String[] args) {

Integer[] arr = {6,6,3,2,4,7};

MergeSort.sortBU(arr);
System.out.println(Arrays.toString(arr));
}
}

class MergeSort {

private MergeSort(){}

public static<E extends Comparable<E>> void sortBU(E[] arr){

E[] temp = Arrays.copyOf(arr, arr.length);

/**
* 遍历要合并的子区间长度，每次长度翻倍
*/
for (int size = 1; size < arr.length; size *= 2) {

/**
* 遍历两个子区间的起始位置，每次相比上次偏移了2倍长度
* 两个子区间为arr[i, i + size - 1]和arr[i + size, i + size + size - 1]
* 注意：数组元素个数不一定为2的整数幂，即最后得到的两个分区间元素个数可能不同，因此i + size + size - 1最终是有可能越界的，需要和数组长度二者来取最小值
*/
for (int i = 0; i + size < arr.length; i = i + 2 * size) {
if (arr[i + size - 1].compareTo(arr[i + size]) > 0) {
mergeBU(arr, i, i + size - 1, Math.min(arr.length - 1, i + 2 * size - 1), temp);
}
}
}
}

public static<E extends Comparable<E>> void mergeBU(E[] arr, int left, int mid, int right, E[] temp) {

int i = left;
int j = mid + 1;

System.arraycopy(arr, left, temp, left, right - left + 1);

for (int n = left; n < right + 1; n++) {

if (i == mid + 1){
arr[n] = temp[j];
j++;
}
else if (j == right + 1) {
arr[n] = temp[i];
i++;
}
else if (temp[i].compareTo(temp[j]) <= 0) {
arr[n] = temp[i];
i++;
}
else{
arr[n] = temp[j];
j++;
}
}
}
}
``````

## 使用插入排序法优化

``````import java.util.Arrays;
import java.util.Random;

public class Algorithm {

public static void main(String[] args) {

Integer[] testScale = {10000, 500000};

for (Integer n : testScale) {

Integer[] randomArr = ArrayGenerator.generatorRandomArray(n, n);

Integer[] sortedArr = ArrayGenerator.generatorSortedArray(n, n);

Integer[] arr1 = Arrays.copyOf(randomArr, randomArr.length);
Integer[] arr3 = Arrays.copyOf(randomArr, randomArr.length);

Integer[] arr2 = Arrays.copyOf(sortedArr, sortedArr.length);
Integer[] arr4 = Arrays.copyOf(sortedArr, sortedArr.length);

System.out.println("测试随机数组排序性能");
System.out.println();

Verify.testTime("sortBU", arr1);
Verify.testTime("sortBU1", arr3);

System.out.println();

System.out.println("测试有序数组排序性能");
System.out.println();

Verify.testTime("sortBU", arr2);
Verify.testTime("sortBU1", arr4);

System.out.println();
}
}
}

class MergeSort {

private MergeSort() {
}

public static <E extends Comparable<E>> void sortBU(E[] arr) {

E[] temp = Arrays.copyOf(arr, arr.length);

for (int size = 1; size < arr.length; size *= 2) {

for (int i = 0; i + size < arr.length; i = i + 2 * size) {
if (arr[i + size - 1].compareTo(arr[i + size]) > 0) {
mergeBU(arr, i, i + size - 1, Math.min(arr.length - 1, i + 2 * size - 1), temp);
}
}
}
}

/**
* 将数组分为长度为16的子区间，用插入排序法实现排序
* 然后从长度16开始，用归并排序法进行合并
*/
public static <E extends Comparable<E>> void sortBU1(E[] arr) {

E[] temp = Arrays.copyOf(arr, arr.length);

for (int i = 0; i < arr.length; i += 16){
InsertionSort.sort(arr, i, Math.min(i + 15, arr.length - 1));
}

for (int size = 16; size < arr.length; size *= 2) {

for (int i = 0; i + size < arr.length; i = i + 2 * size) {
if (arr[i + size - 1].compareTo(arr[i + size]) > 0) {
mergeBU(arr, i, i + size - 1, Math.min(arr.length - 1, i + 2 * size - 1), temp);
}
}
}
}

public static <E extends Comparable<E>> void mergeBU(E[] arr, int left, int mid, int right, E[] temp) {

int i = left;
int j = mid + 1;

System.arraycopy(arr, left, temp, left, right - left + 1);

for (int n = left; n < right + 1; n++) {

if (i == mid + 1) {
arr[n] = temp[j];
j++;
} else if (j == right + 1) {
arr[n] = temp[i];
i++;
} else if (temp[i].compareTo(temp[j]) <= 0) {
arr[n] = temp[i];
i++;
} else {
arr[n] = temp[j];
j++;
}
}
}
}

class InsertionSort {

private InsertionSort() {}

public static <E extends Comparable> void sort(E[] arr, int left, int right) {

for (int i = left + 1; i < right + 1; i++) {

E tem = arr[i];
int j;

for (j = i; j > left && tem.compareTo(arr[j - 1]) < 0; j--) {

arr[j] = arr[j - 1];
}

arr[j] = tem;
}
}
}

class ArrayGenerator {

private ArrayGenerator (){}

public static Integer[] generatorRandomArray (Integer n, Integer maxBound){

Integer[] arr = new Integer[n];

Random random = new Random();

for (int i = 0; i < n; i++) {

arr[i] = random.nextInt(maxBound);
}

return arr;
}

public static Integer[] generatorSortedArray (Integer n, Integer maxBound){

Integer[] arr = new Integer[n];

for (int i = 0; i < n; i++) {

arr[i] = i;
}

return arr;
}
}

class Verify {

private Verify (){}

public static<E extends Comparable<E>> boolean isSorted(E[] arr){

for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
return false;
}
}

return true;
}

public static<E extends Comparable<E>> void testTime(String AlgorithmName, E[] arr) {

long startTime = System.nanoTime();

if (AlgorithmName.equals("sortBU")) {
MergeSort.sortBU(arr);
}

if (AlgorithmName.equals("sortBU1")) {
MergeSort.sortBU1(arr);
}

long endTime = System.nanoTime();

if (!Verify.isSorted(arr)){
throw new RuntimeException(AlgorithmName + "算法排序失败！");
}

System.out.println(String.format("%s算法，测试用例为%d，执行时间：%f秒", AlgorithmName, arr.length, (endTime - startTime) / 1000000000.0));
}
}
``````

## 自顶向下和自底向上性能比较

``````import java.util.Arrays;
import java.util.Random;

public class Algorithm {

public static void main(String[] args) {

Integer[] testScale = {10000, 500000};

for (Integer n : testScale) {

Integer[] randomArr = ArrayGenerator.generatorRandomArray(n, n);

Integer[] sortedArr = ArrayGenerator.generatorSortedArray(n, n);

Integer[] arr1 = Arrays.copyOf(randomArr, randomArr.length);
Integer[] arr3 = Arrays.copyOf(randomArr, randomArr.length);
Integer[] arr5 = Arrays.copyOf(randomArr, randomArr.length);

Integer[] arr2 = Arrays.copyOf(sortedArr, sortedArr.length);
Integer[] arr4 = Arrays.copyOf(sortedArr, sortedArr.length);
Integer[] arr6 = Arrays.copyOf(sortedArr, sortedArr.length);

System.out.println("测试随机数组排序性能");
System.out.println();

Verify.testTime("sortOptimised1", arr1);
Verify.testTime("sortOptimised2", arr3);
Verify.testTime("sortBU", arr5);

System.out.println();

System.out.println("测试有序数组排序性能");
System.out.println();

Verify.testTime("sortOptimised1", arr2);
Verify.testTime("sortOptimised2", arr4);
Verify.testTime("sortBU", arr6);

System.out.println();
}
}
}

class MergeSort {

private MergeSort(){}

/**
* 优化一：有序数组优化，合并前先判断一下是否需要合并
*/
public static<E extends Comparable<E>> void sortOptimised1(E[] arr){

sortOptimised1(arr, 0, arr.length - 1);
}

private static<E extends Comparable<E>> void sortOptimised1(E[] arr, int left, int right){

if (left >= right){
return;
}

int mid = left + (right - left) / 2;

sortOptimised1(arr, left, mid);
sortOptimised1(arr, mid + 1, right);

if (arr[mid].compareTo(arr[mid + 1]) > 0) {
merge(arr, left, mid, right);
}
}

/**
* 优化三：内存操作优化
*/
public static<E extends Comparable<E>> void sortOptimised2(E[] arr){

/**
* 提前将arr数组保存一个副本，这样就不用每次调用merge()方法，都重新开辟空间新建一个数组了
*/
E[] temp = Arrays.copyOf(arr, arr.length);

sortOptimised2(arr, 0, arr.length - 1, temp);
}

private static<E extends Comparable<E>> void sortOptimised2(E[] arr, int left, int right, E[] temp){

if (left >= right){
return;
}

int mid = left + (right - left) / 2;

sortOptimised2(arr, left, mid, temp);
sortOptimised2(arr, mid + 1, right, temp);

if (arr[mid].compareTo(arr[mid + 1]) > 0) {
mergeOptimised(arr, left, mid, right, temp);
}
}

/**
* 自底向上归并排序法
*/
public static<E extends Comparable<E>> void sortBU(E[] arr){

E[] temp = Arrays.copyOf(arr, arr.length);

for (int size = 1; size < arr.length; size *= 2) {

for (int i = 0; i + size < arr.length; i = i + 2 * size) {
if (arr[i + size - 1].compareTo(arr[i + size]) > 0) {
mergeBU(arr, i, i + size - 1, Math.min(arr.length - 1, i + 2 * size - 1), temp);
}
}
}
}

public static<E extends Comparable<E>> void mergeBU(E[] arr, int left, int mid, int right, E[] temp) {

int i = left;
int j = mid + 1;

System.arraycopy(arr, left, temp, left, right - left + 1);

for (int n = left; n < right + 1; n++) {

if (i == mid + 1){
arr[n] = temp[j];
j++;
}
else if (j == right + 1) {
arr[n] = temp[i];
i++;
}
else if (temp[i].compareTo(temp[j]) <= 0) {
arr[n] = temp[i];
i++;
}
else{
arr[n] = temp[j];
j++;
}
}
}

public static<E extends Comparable<E>> void merge(E[] arr, int left, int mid, int right) {

int i = left;
int j = mid + 1;

E[] tem = Arrays.copyOfRange(arr, left, right + 1);

for (int n = left; n < right + 1; n++) {

if (i == mid + 1){
arr[n] = tem[j - left];
j++;
}
else if (j == right + 1) {
arr[n] = tem[i - left];
i++;
}
else if (tem[i - left].compareTo(tem[j - left]) <= 0) {
arr[n] = tem[i - left];
i++;
}
else{
arr[n] = tem[j - left];
j++;
}
}
}

/**
* 优化merge()方法，复用temp数组，节省空间
*/
public static<E extends Comparable<E>> void mergeOptimised(E[] arr, int left, int mid, int right, E[] temp) {

int i = left;
int j = mid + 1;

/**
* System.arraycopy()方法将传过来的排好序的两个分数组在相同位置赋值给副本数组temp，因此索引范围一致没有偏移
*/
System.arraycopy(arr, left, temp, left, right - left + 1);

for (int n = left; n < right + 1; n++) {

if (i == mid + 1){
arr[n] = temp[j];
j++;
}
else if (j == right + 1) {
arr[n] = temp[i];
i++;
}
else if (temp[i].compareTo(temp[j]) <= 0) {
arr[n] = temp[i];
i++;
}
else{
arr[n] = temp[j];
j++;
}
}
}
}

class ArrayGenerator {

private ArrayGenerator (){}

public static Integer[] generatorRandomArray (Integer n, Integer maxBound){

Integer[] arr = new Integer[n];

Random random = new Random();

for (int i = 0; i < n; i++) {

arr[i] = random.nextInt(maxBound);
}

return arr;
}

public static Integer[] generatorSortedArray (Integer n, Integer maxBound){

Integer[] arr = new Integer[n];

for (int i = 0; i < n; i++) {

arr[i] = i;
}

return arr;
}
}

class Verify {

private Verify (){}

public static<E extends Comparable<E>> boolean isSorted(E[] arr){

for (int i = 0; i < arr.length - 1; i++) {
if (arr[i].compareTo(arr[i + 1]) > 0) {
return false;
}
}

return true;
}

public static<E extends Comparable<E>> void testTime(String AlgorithmName, E[] arr) {

long startTime = System.nanoTime();

if (AlgorithmName.equals("sortOptimised1")) {
MergeSort.sortOptimised1(arr);
}

if (AlgorithmName.equals("sortOptimised2")) {
MergeSort.sortOptimised2(arr);
}

if (AlgorithmName.equals("sortBU")) {
MergeSort.sortBU(arr);
}

long endTime = System.nanoTime();

if (!Verify.isSorted(arr)){
throw new RuntimeException(AlgorithmName + "算法排序失败！");
}

System.out.println(String.format("%s算法，测试用例为%d，执行时间：%f秒", AlgorithmName, arr.length, (endTime - startTime) / 1000000000.0));
}
}
``````