算法描述
归并排序是采用分治法(Divide and Conquer)的一个非常典型的应用。即先使每个子序列有序,再使子序列段间有序,再将已有序的子序列合并,得到完全有序的序列。将两个有序表合并成一个有序表,称为2-路归并。以此类推,有3-路归并等。算法流程如下:
- 把长度为n的输入序列分成两个长度为n/2的子序列;
- 对这两个子序列分别采用归并排序;
- 将两个排序好的子序列合并成一个最终的排序序列。
动画展示
代码实现
public class MergeSort {
public static void main(String[] args) {
int[] arr = CommonStant.ARR;
int length = arr.length;
int[] temp = new int[length];
sort(arr,0,length-1,temp);
Arrays.stream(arr).forEach(System.out::println);
}
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 leftP = left;
int rightP = mid+1;
int tempIndex = 0;
while (leftP<=mid&&rightP<=right){
if (arr[leftP] < arr[rightP]){
temp[tempIndex++] = arr[leftP++];
}else {
temp[tempIndex++] = arr[rightP++];
}
}
while(leftP<=mid){
temp[tempIndex++] = arr[leftP++];
}
while(rightP<=right){
temp[tempIndex++] = arr[rightP++];
}
tempIndex = 0;
while(left<=right){
arr[left++] = temp[tempIndex++];
}
}
}
总结
稳定性:算法稳定,归并排序在排序前后两个相等的数相对位置不变。
时间复杂度:O(nlogn),最好情况O(nlogn), 最坏情况O(nlogn)。
空间复杂度:O(n),需要额外的变量进行存储。