1.介绍:
归并排序(Merge Sort)是建立在归并操作上的一种有效,稳定的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。
2.我们需要将两个已经有序的子序列合并成一个有序序列,比如上图最后一次合并,将[2,4,5,6]和[1,3,7,8]已经有序的子序列合并最终序列[1,2,3,4,5,6,7,8]
3.代码实现:
package sort;
import java.util.Arrays;
/**
* @author WuChenGuang
*/
public class MergeSort {
public static void main(String[] args) {
int[] array = new int[]{6, 9, 4, 7, 1, 2, 0, 5, 3, 8};
// 临时数组
int[] temp = new int[array.length];
sort(array, 0, array.length - 1, temp);
System.out.println(Arrays.toString(array));
}
public static void sort(int[] array, int left, int right, int[] temp) {
if (left < right) {
// 求出中间值
int mid = (left + right) / 2;
// 向左边分解
sort(array, left, mid, temp);
// 向右边分解
sort(array, mid + 1, right, temp);
// 合并数据
sum(array, left, right, mid, temp);
}
}
/**
* 合并元素
*/
public static void sum(int[] array, int left, int right, int mid, int[] temp) {
int i = left;
int j = mid + 1;
// 指向临时数组下标
int t = 0;
// 开始循环比较左右两遍数组元素比较
while (i <= mid && j <= right) {
if (array[i] <= array[j]) {
temp[t] = array[i];
t++;
i++;
} else {
temp[t] = array[j];
t++;
j++;
}
}
// 把剩余的元素直接存放在临时数组中
while (i <= mid) {
temp[t] = array[i];
t++;
i++;
}
while (j <= right) {
temp[t] = array[j];
t++;
j++;
}
// 临时数组中的元素拷贝至原数组中
int tempIndex = left;
int k = 0;
while (tempIndex <= right) {
array[tempIndex] = temp[k];
k++;
tempIndex++;
}
}
}
运行结果: