灯神讲解视频:https://www.bilibili.com/video/av9982752?from=search&seid=389996237580366908
public class MergeSort {
public void printArr(int arr[]){
for (int i = 0; i < arr.length; i++) {
System.out.printf(arr[i]+"\t");
}
System.out.println();
}
public void mergeSortInner(int arr[], int left, int middle, int right) {
final int LEFT_SIZE = middle - left;
final int RIGHT_SIZE = right - middle+1;
int[] leftPart = new int[LEFT_SIZE];
int[] rightPart = new int[RIGHT_SIZE];
for (int i = left; i < middle; i++) {
leftPart[i - left] = arr[i];
}
printArr(leftPart);
for (int i = middle; i <= right; i++) {
rightPart[i - middle] = arr[i];
}
printArr(rightPart);
int l = 0;
int r = 0;
int t = left;
while (l < LEFT_SIZE && r < RIGHT_SIZE) {
if (leftPart[l] < rightPart[r]) {
arr[t] = leftPart[l];
l++;
t++;
} else {
arr[t] = rightPart[r];
r++;
t++;
}
}
printArr(arr);
while (l<LEFT_SIZE){
arr[t] = leftPart[l];
l++;
t++;
}
printArr(arr);
while (r<RIGHT_SIZE){
arr[t] = rightPart[r];
r++;
t++;
}
}
public void mergeSort(int arr[],int left,int right) {
if (left == right){
return;
}else{
int middle = (left+right)/2;
mergeSort(arr,left,middle);
mergeSort(arr,middle+1,right);
mergeSortInner(arr,left,middle+1,right);
}
}
public static void main(String[] args) {
int arr[] = {
2,8,9,10,4,5,6,7};
int l = 0;
int r = arr.length-1;
int m = 4;
new MergeSort().mergeSort(arr,l,r);
for (int i = 0; i < arr.length; i++) {
System.out.printf(arr[i]+"\t");
}
}
}