归并排序(Merge Sort):
1、原理
归并排序是一种概念上最简单的排序算法,与快速排序一样,归并排序也是基于分治法的。归并排序将待排序的元素序列分成两个长度相等的子序列,为每一个子序列排序,然后再将他们合并成一个子序列。合并两个子序列的过程也就是两路归并。
2、核心思想:
-
将数组拆分为两个数组,然后对两个数组各自进行排序。
-
合并两个排好序的数组。
3、复杂度
归并排序是一种稳定的排序算法,归并排序的主要问题在于它需要一个与待排序数组一样大的辅助数组空间。由于归并排序每次划分时两个子序列的长度基本一样,所以归并排序最好、最差和平均时间复杂度都是nlog2n。
我们可以通过下图非常容易看懂归并排序的过程:
![](https://i-blog.csdnimg.cn/blog_migrate/f8faa4f52fe17281ef6a5391a74e7f7c.gif)
public class MergetSort {
public static void main(String[] args) {
int arr[]={8,4,5,7,1,3,6,2};
int temp[]=new int[arr.length];
MergetSort(arr,0,arr.length-1,temp);
//输出排好序后的数组
System.out.println(Arrays.toString(arr));
}
public static void MergetSort(int arr[],int left,int right,int temp[]){
if(left<right){
//中间索引
int mid=(left+right)/2;
//向左递归进行分解
MergetSort(arr,left,mid,temp);
//向右递归进行分解
MergetSort(arr,mid+1,right,temp);
//进行合并
Merge(arr,left,mid,right,temp);
}
}
public static void Merge(int arr[],int left,int mid,int right,int temp[]){
//左索引
int i=left;
//右索引
int j=mid+1;
//数组temp索引
int t=0;
//一
//先把左右两边有序的数据填充到temp数组
//直到一边的数据处理完毕
while(i<=mid&&j<=rigth){
//如果左边的数据小于右边的数据,即将左边的当前元素填充到temp数组
//然后t++,i++
if(arr[i]<arr[j]){
temp[t]=arr[i];
t++;
i++;
}else{
//反之,将右边的当前元素填充到tempp数组
//t++,j++
temp[t]=arr[j];
t++;
j++
}
}
//(二)
//如果左边索引小于中间索引,说明左边的数据没有处理完,即将左边的有序序列按照顺序加入到temp中
while(i<=mid){
temp[t]=arr[i];
t++;
i++;
}
//如果右边索引小于左边边界,说明右边的元素还没有处理完,即将右边的有序序列按照顺序加入到temp中
while(j<=right){
temp[t]=arr[j];
t++;
j++;
}
//(三)
//(将temp数组中的元素拷贝到arr数组中)
//注意,不是每次都拷贝所有
t=0;
int tempLeft=left;
while(tempLeft<=right){
arr[tempLeft]=temp[t];
t++;
tempLeft++;
}
}
}