package 归并排序1;
public class MergeSort2 {
public static void main(String[] args) {
int[] arr = {1, 4, 7, 8, 3, 6, 9};
sort(arr,0, arr.length-1);
print(arr);
}
public static void sort(int[] arr,int left,int right) {
if(left==right)return;//递归终止条件
//分成俩半
int mid=left+(right-left)/2;//防止越界
//左边排序
sort(arr,left,mid);
//右边排序
sort(arr,mid+1,right);
merge(arr,left,mid+1,right);
}
public static void merge(int[] arr, int leftPtr, int rightPtr, int rightBound) {
int[] temp = new int[rightBound - leftPtr+1];//开辟一块新空间,数组名为temp
int i = leftPtr;//用于遍历左数组
int mid = rightPtr-1;//分割的位置
int j = mid + 1;//用于遍历右数组
int k = 0;//用于遍历新数组
while (i <= mid && j <= rightBound) {
temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];//最简化
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= rightBound) {
temp[k++] = arr[j++];
}
for(int m=0;m<temp.length;m++)arr[leftPtr+m]=temp[m];//把temp数组的东西方到arr数组去
}
public static void print(int[] arr) {
System.out.print("{");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr[i]);
} else {
System.out.print(arr[i] + ", ");
}
}
System.out.print("}");
}
}