一.概念
案例:
如何将两个有序序列归并为一个有序序列,两个序列本身有序
二.实现
public class MergeSort {
public static void main(String[] args) {
int a[] = new int[]{1, 6, 9, 4, 7, 3, 8, 2};
sort(a,0,a.length-1);
int x=0;
while (x<a.length){
System.out.print(a[x++]);
}
}
private static void sort(int[] a, int low, int high) {
if (low<high){
int mid = (low+high)/2;
sort(a,low,mid);
sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
//数组a被分为两部分, low-mid 是第一部分的索引范围, mid+1-high第二部分的索引范围,超出这两个范围的元素不是此合并的部分
//把这两部分合并
private static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
while (j <= high) {
temp[k++] = a[j++];
}
while (i <= mid) {
temp[k++] = a[i++];
}
//把temp 复制到a, 小于low 大于high的元素不能变
for (int x = 0; x < temp.length; x++) {
a[low + x] = temp[x];
}
}
}
三.算法分析
时间复杂度:用二路归并,需要logn趟,每趟归并的时间为O(n),所以时间复杂度是O(nlogn),并且最坏最好都是这样。