合併排序

合併算法:

package test1;


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;//i是前一個數組的開頭
        int j=m+1;//下一個數組的開頭
        int c=0;//是一個計數器,用來計算數組a的序列
        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){//對於特殊的序列,i未進行
            temp[c]=arrays[i];
            i++;
        }
        while(j<=end){//對於特殊的序列,j未進行
        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[]={5,4,9,7};
        m.merge_sort(a,0,a.length-1);

    }

}



描述排序
對於合併排序來講:
1,先把數組用分治法進行劃分,分爲最小的基本單位
2.進行排序,可以分爲幾種排序方法,舉個簡單的例子,現在有四個數a,b,和c,d
進行排序有幾種情況:

快速排序:
//快速排序

void quick_sort(int s[], int l, int r)  
{  
    if (l < r)  
    {  
        //Swap(s[l], s[(l + r) / 2]); //將中間的這個數和第一個數交換 參見注1  
        int i = l, j = r, x = s[l];  
        while (i < j)  
        {  
            while(i < j && s[j] >= x) // 從右向左找第一個小於x的數  
                j--;    
            if(i < j)   
                s[i++] = s[j];  

            while(i < j && s[i] < x) // 從左向右找第一個大於等於x的數  
                i++;    
            if(i < j)   
                s[j--] = s[i];  
        }  
        s[i] = x;  
        quick_sort(s, l, i - 1); // 遞歸調用   
        quick_sort(s, i + 1, r);  
    }  
}  

//參考:http://blog.csdn.net/morewindows/article/details/6684558
http://www.cnblogs.com/luchen927/archive/2012/02/29/2368070.html

//參考:http://www.cnblogs.com/yangecnu/p/Introduce-Merge-Sort.html
參考文檔:http://www.cnblogs.com/yangecnu/p/Introduce-Merge-Sort.html#

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章