归并排序
基本原理:
(Merge Sort)是建立在归并操作上的一种排序算法,该算法是采用分治法(Divide and
Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个
子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并,使用中
牺牲空间换取时间的算法。
给定的数组两边不是有序的怎么办?
分治法把两边分别进行归并,一分为2,左右分别归并,如果不符合要求继续一分为二,直到两边
只有一个数(一个数一定是有序的)
public 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(i<=mid){
temp[k++] = a[i++];
}
// 把右边边剩余的数移入数组
while(j<=high){
temp[k++] = a[j++];
}
// 把新数组中的数覆盖nums数组
for(int x=0;x<temp.length;x++){
a[x+low] = temp[x];
}
}
public static void mergeSort(int[] a, int low, int high){
int mid = (low+high)/2;
if(low<high){
mergeSort(a,low,mid);
mergeSort(a,mid+1,high);
//左右归并
merge(a,low,mid,high);
}
}