归并排序
核心:将数据分为单个数据,对单个数据进行不断组合并排序
关键词:分治
动图
代码
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);
}
}
/**
* 合并方法
*
* @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;// 左边部分索引
int j = mid + 1;// 右边部分索引
int t = 0;// temp的索引
// 先把左右两边的数据按照规则放入temp知道左右两边有一边没有数据
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[t] = arr[i];
t++;
i++;
} else {
temp[t] = arr[j];
t++;
j++;
}
}
// 把剩余的数据依次放入temp
// 左边数组有剩余
while (i <= mid) {
temp[t] = arr[i];
t++;
i++;
}
// 右边有剩余
while (j <= right) {
temp[t] = arr[j];
t++;
j++;
}
// 将temp数组的元素拷贝到arr
t = 0;
int leftTemp = left;
while (leftTemp <= right){
arr[leftTemp] = temp[t];
t++;
leftTemp++;
}
}
本文动图来源:https://www.cnblogs.com/onepixel/p/7674659.html