归并排序思路:
一、分解
二、合并
- 进行比较两端数组
- 对剩余数组放进temp
三、将temp数组拷贝到原数组中
代码:
main函数
public static void main(String[] args) {
int[] arr = {5,4,3,1,2,6,7,9,8};
int[] tmp = new int[arr.length];
mergeInternal(arr,0,arr.length-1,tmp);
System.out.println(Arrays.toString(arr));
}
分解代码:
// 分解
public static void mergeInternal(int[] arr, int low, int hight, int[] temp){
if(low >= hight){
return;
}
int mid = (low + hight) / 2;
mergeInternal(arr, low, mid, temp);
mergeInternal(arr, mid + 1, hight, temp);
//当分解到最后开始合并
merge(arr,low,mid,hight,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索引
//先比较两边的数组
while(i <= mid && j <= right){
if(arr[i] <= arr[j]){
temp[t] = arr[i];
t++;
i++;
}
else{
temp[t] = arr[j];
t++;
j++;
}
}
// 将剩余一端数组放进去
while(i <= mid){
temp[t] = arr[i];
t++;
i++;
}
while(j <= right){
temp[t] = arr[j];
t++;
j++;
}
// 将temp 数组拷贝到原数组
t = 0;
int templeft = left;
while (templeft <= right){
arr[templeft] = temp[t];
t++;
templeft++;
}