# 2.3.1 归并排序(分治法)

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");
}
}
}
04-22 1887

05-18 840
09-22 47
08-11 209
06-12 157
04-22 75
03-21 219
02-11 179