归并排序介绍
归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题分(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。
算法复杂度
图解
归并子序列图解
代码
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr={8,4,5,7,1,3,6,2};
int[] temp=new int[arr.length];
System.out.println("初始数据为:"+Arrays.toString(arr));
mergeSort(arr,0,arr.length-1,temp);
System.out.println("新的数据为:"+Arrays.toString(arr));
}
/**
* 归并排序
*/
public static void mergeSort(int[] arr,int left,int right,int[] temp ){
int mid=(left+right)/2;
if(left<right){
//右侧分
mergeSort(arr,left,mid,temp);
//左侧分
mergeSort(arr,mid+1,right,temp);
//合并
merge(arr,left,right,mid,temp);
}
}
/**
*合并数组
* @param arr 要排序的数组(参与合并的不一定是arr的全部数据,最后一次才是把全部数据合并)
* @param left 数组的左侧指针
* @param right 数组右侧指针
* @param mid 数组中间指针
*/
public static void merge(int[] arr,int left,int right,int mid,int[] temp){
int i=left;//右侧数组指针
int j=mid+1;//左侧数组指针
int t=0; //temp数组下标
//第一步排序到temp数组
while(i<=mid&&j<=right){
if(arr[i]<=arr[j]){
temp[t++]=arr[i];
i+=1;
}
if (arr[j]<arr[i]){
temp[t++]=arr[j];
j+=1;
}
}
//第二步解决右侧或左侧排序完另一侧还有剩余的情况
while(i<=mid){
temp[t++]=arr[i++];
}
while (j<=right){
temp[t++]=arr[j++];
}
//第三步 把在temp数组排好序的数据赋值到arr中
int tempLeft=0;
while (tempLeft<t){
arr[left++]=temp[tempLeft++];
}
}
运行结果