合併排序要比前面兩種排序要稍複雜些。合併排序是在算法中分治思想的一個很好的實例,接下來我們一起來學習合併排序是如何實現的。
首先我先給大家展示一張圖:
從上圖中我們可以看出,首先我們對一個序列進行分割,直至分到最小單元時,然後對最小的單元進行排序,然後把兩個排好序的單元進行合併。此處劃分到最小單元就是一個分治算法的體現,如果大家對分治算法不明白的可以去查找相關的資料學習,分治算法是解決問題的一個非常好的辦法,有句俗語就是說明了這個道理“大事化小,小事化了”,可見我們的祖先是多麼的聰明。接下來直接給大家上代碼,如果有問題的可以提出來:
package gzw.pkg1;
/**
* Created by Toplife on 2014/11/2.
*/
public class Merge
{
//遞歸分成小部分
public void merge_sort(int[] arrays,int start,int end){
if(start<end){
int m=(start+end)/2;
merge_sort(arrays,start,m);
merge_sort(arrays,m+1,end);
combin_arrays(arrays,start,m,end);
}
}
//合併數組
public void combin_arrays(int[] arrays,int start,int m,int end){
int length=end-start+1;
int temp[]=new int[length];//用來存放比較的數組,用完複製回到原來的數組
int i=start;
int j=m+1;
int c=0;
while(i<=m &&j<=end){
if(arrays[i]<arrays[j]){
temp[c]=arrays[i];
i++;
c++;
}else{
temp[c]=arrays[j];
j++;
c++;
}
}
while(i<=m){
temp[c]=arrays[i];
i++;
}
while(j<=end){
temp[c]=arrays[j];
j++;
}
c=0;
for(int t=start;t<=end;t++,c++){
arrays[t]=temp[c];
}
snp(arrays);
}
//打印數組
public void snp(int[] arrays){
for(int i=0;i<arrays.length;i++){
System.out.print(arrays[i]+" ");
}
System.out.println();
}
public static void main(String[] args)
{
Merge m=new Merge();
int a [] ={8,3,2,9,7,1,5,4};
m.merge_sort(a,0,a.length-1);
}
}
Live as if you were to die tomorrow. Learn as if you were to live forever.