歸併排序
歸併(Merge)排序法是將兩個(或兩個以上)有序集合合併成一個新的有序表,即把待排序序列分爲若干個子序列,每個子序列是有序的。然後再把有序子序列合併爲一個有序序列。
合併過程
設r[i…n]由兩個有序子表r[i…m]和r[m+1…n]組成,兩個子表長度分別爲n-i +1、n-m。
1. j=m+1;k=i;i=i; //置兩個子表的起始下標及輔助數組的起始下標
2. 若i>m 或j>n,轉⑷ //其中一個子表已合併完,比較選取結束
3. //選取r[i]和r[j]較小的存入輔助數組rf
如果r[i] < r[j],rf[k]=r[i]; i++; k++; 轉⑵
否則,rf[k]=r[j]; j++; k++; 轉⑵
4. //將尚未處理完的子表中元素存入rf
如果i<=m,將r[i…m]存入rf[k…n] //前一子表非空
如果j<=n , 將r[j…n] 存入rf[k…n] //後一子表非空
5. 合併結束。
代碼示例
/**
* 歸併排序
*
* @author yangpeng
*
*/
public class MergeSortDemo {
public static void main(String[] args) {
int[] a = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
System.out.println("初始數組:" + Arrays.toString(a));
mergeSort(a,0,a.length-1);
System.out.println("最後排序後數組:" + Arrays.toString(a));
}
static int count=0;
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);
System.out.println((++count)+"排序後數組:" + Arrays.toString(a));
}
}
/**
* 左右合併
*
* @param a
* 排序的數組
* @param low
* 左索引
* @param mid
* 中間索引
* @param 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 (i <= mid) {
temp[k++] = a[i++];
}
// 把右邊剩餘的數移入數組
while (j <= high) {
temp[k++] = a[j++];
}
// 把新數組的值 覆蓋原數組的值
for (int k2 = 0; k2 < temp.length; k2++) {
a[k2+low]=temp[k2];
}
}
}