归并排序思想:
归并排序是采用的一种分治思想,递归解决;
如图所示,首先将序列拆分,拆成前一半和后一半,继续对子序列拆分,直到拆分为一个子序列只有一个数为止,然后再将子序列一步步合并成为一个有序序列;
合并序列的代码:
/**
*
* @param arr 需要排序的原始数组
* @param left 左边有序序列的初始索引
* @param mid 中间索引
* @param right 右边索引
* @param temp 作中转的数组
*/
public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left; //初始化i,左边有序序列的初始索引
int j = mid + 1; //初始化j,右边有序序列的初始索引
int t = 0; //指向temp数组的当前索引
//(1)
//先把左右两边(有序)的数据按照规则填充到temp数组中
//直到左右两边的有序序列,有一边处理完为止
while (i <= mid && j <= right) {
//如果左边的有序序列当前元素,小于等于右边有序序列的当前元素,就把该元素拷贝到temp数组中
if (arr[i] <= arr[j]) {
temp[t] = arr[i];
t++;
i++;
}
else { //反之,将右边有序序列中的当前元素拷贝到temp数组中
temp[t] = arr[j];
t++;
j++;
}
}
//(2)
//把有剩余数据的一边的数据依次填充到temp中
while (i <= mid) {
temp[t] = arr[i];
t++;
i++;
}
while (j <= right) {
temp[t] = arr[j];
t++;
j++;
}
//(3)
//将temp数组的元素拷贝到arr中
//注意,并不是每一次都需要拷贝所有元素回到arr中
t = 0;
int tempLeft = left;
// System.out.println("tempLeft = " + tempLeft + "\tRight = " + right);
while (tempLeft <= right) { //
arr[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
拆分 + 合并代码
public static void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2; //中间索引
//向左递归进行分解
mergeSort(arr,left,mid,temp);
//向右递归进行分解
mergeSort(arr, mid + 1, right, temp);
//合并
merge(arr,left,mid,right,temp);
}
}