https://www.bilibili.com/video/BV1Zt411o7Rn?p=25
参考:这个视频借鉴的归并写法
主要逻辑在对排好后的两个数组进行归并逻辑,
就是有一个指向第一个数组的指针 i
有一个指向第二个数组的指针 j
进行比较并将小的结果放进临时数组,直到一方遍历完成为止,然后再把没有遍历完的数组依次进入数组即可
private static void mergeSort(int[] arr, int start , int end){ if(start >= end){ return; } int mid = (end + start) / 2; mergeSort(arr,start,mid); mergeSort(arr,mid+1,end); merge(arr,start,mid ,end); } private static void merge(int[] arr, int start, int mid, int end) { int[] temp = new int[end - start + 1]; int leftIndex = start; int rightIndex = mid + 1; int index = 0; while (leftIndex <= mid && rightIndex <= end ){ if(arr[leftIndex] < arr[rightIndex]){ temp[index] = arr[leftIndex]; leftIndex++; }else { temp[index] = arr[rightIndex]; rightIndex++; } index++; } while (leftIndex <= mid){ temp[index] = arr[leftIndex]; leftIndex++; index++; } while (rightIndex <= end){ temp[index] = arr[rightIndex]; rightIndex++; index++; } for (int i = 0; i < temp.length; i++) { arr[start + i] = temp[i]; } }