思路:归并排序是把一个无序的数组,分割成若干个小块,没快排序,整合,在排序,最后合成完成数组的过程。过程分为1.分割2.整合
图解:图片来自https://www.cnblogs.com/chengxiao/p/6194356.html
2个数组合成情况如下图所示:这里要把内容移动一个新的数组中,排序完成后再copy到原数组。
每次左右比较吧小的数放到新的数组中。
详细代码:
package rank;
public class MergeRank { // 合并排序
public static void main(String[] args) {
int[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int[] temp = new int[arr.length];
temp = sort(arr, 0, arr.length - 1, temp);
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i] + "--");
}
}
/*
* sort 方法用于吧一个数组 分组,调用merge方法进行排序
*/
public static int[] sort(int[] arr, int left, int right, int[] temp) {
int mid = (left + right) / 2;
if (left < right) {
sort(arr, left, mid, temp);// 左边多次调用 多次分组,使得左边有序
sort(arr, mid + 1, right, temp);// 右边有序
temp = merge(left, mid, right, arr, temp); // 排序 并合并合并
}
return temp;
}
public static int[] merge(int left, int mid, int right, int[] arr, int[] temp) {
int i = left;
int j = mid + 1;
int num = 0;
while (left <= mid && j <= right) {// 保证左右不越界
if (arr[left] < arr[j]) {// 判断左右2边大小 //小的放到新数组中
temp[num] = arr[left];
num++;
left++;
} else {
temp[num] = arr[j];
num++;
j++;
}
}
while (left <= mid) { // 吧左边或者右边剩余的数放到数组中
temp[num] = arr[left];
left++;
num++;
}
while (j <= right) {
temp[num] = arr[j];
j++;
num++;
}
num = 0;
while (i <= right) { // 吧有序数组的内容放到数组
arr[i] = temp[num];
i++;
num++;
}
return temp;
}
}