归并排序的的核心思想是:
1.使待排序列的左右两半部分都是有序的。
2.合并有序的两半部分。
详见代码(源码面前。了无秘密)
package com.dlut.sort;
import org.junit.Test;
public class MergeSort {
private int[] arr = {9,0,1,3,2,5,4,7,6,8,100,12,11,13,14,17,16,15,34};
@Test
public void printMergeSort()
{
int[] tempArr = new int[arr.length];
mergeSort(arr, tempArr, 0, arr.length-1);
for (int j = 0; j < tempArr.length; j++) {
System.out.println(tempArr[j]);
}
}
/**
* 使数组左右两半部分都有序,然后就可以执行合并函数
* @param arr
* @param tempArr
* @param low
* @param high
*/
public void mergeSort(int[] arr,int[] tempArr,int low,int high)
{
if (low<high) {
int center = (low+high)/2;
mergeSort(arr, tempArr, low, center);
mergeSort(arr, tempArr, center+1, high);
mergeArr(arr, tempArr, center, low, high);
}
}
/**
* 合并函数:合并两个相邻的有序的数组
* @param arr
* @param tempArr
* @param center
* @param low
* @param high
*/
public void mergeArr(int[] arr,int[] tempArr,int center,int low,int high)
{
int leftlow = low,temppos = low;
int rightlow = center + 1;
while (leftlow <=center && rightlow <= high) {
if (arr[leftlow]<=arr[rightlow]) {
tempArr[temppos++] = arr[leftlow++];
}
else {
tempArr[temppos++] = arr[rightlow++];
}
}
while (leftlow <=center)
tempArr[temppos++] = arr[leftlow++];
while (rightlow <= high)
tempArr[temppos++] = arr[rightlow++];
/*
* 这一步是必须的,因为你是在arr上进行归并排序。一定要将本次的结果放到arr上。
* 试想如果没有放入arr中,则会出现,某一位置的元素经过多次的交换后又回到该位置
*/
for (int i = low; i <= high; i++) {
arr[i] = tempArr[i];
}
}
}