歸併排序
阿新 • • 發佈:2020-07-04
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]; } }