主要思想:
归并排序主要思想是采用分治法,将大问题分成多个小问题,然后在治的阶段将分阶段得到的小问题合并起来,就是分而治之。
分治概略图:
合并策略:
代码实现:
public class MergeSort {
public static void main(String []args){
int []arr = {8,4,5,7,1,3,6,2};
sort(arr);
System.out.println(Arrays.toString(arr));
}
public static void sort(int []arr){
int []temp = new int[arr.length];
sort(arr,0,arr.length - 1,temp);
}
private static void sort(int[] arr,int left,int right,int []temp){
if(left<right){
int mid = (left+right) / 2;
//左边归并排序,使得左子序列有序
sort(arr,left,mid,temp);
//右边归并排序,使得右子序列有序
sort(arr,mid+1,right,temp);
//将两个有序子数组合并操作
merge(arr,left,mid,right,temp);
}
}
private static void merge(int[] arr,int left,int mid,int right,int[] temp){
//左序列指针
int i = left;
//右序列指针
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right){
if(arr[i] <= arr[j]){
temp[t++] = arr[i++];
}else {
temp[t++] = arr[j++];
}
}
//将左边剩余元素填充进temp中
while(i <= mid){
temp[t++] = arr[i++];
}
//将右序列剩余元素填充进temp中
while(j <= right){
temp[t++] = arr[j++];
}
t = 0;
//将temp中的元素全部拷贝到原数组中
while(left <= right){
arr[left++] = temp[t++];
}
}
}