归并排序

归并排序基于两个已排好序的序列合成一个排好的序列的思想。

//归并排序
public class MergeSort 
{
    public void mergeSort(int[] a,int low,int high)
    {
        if(low<high)
        {
            mergeSort(a,low,(low+high)/2);
            mergeSort(a,(low+high)/2+1,high);
            merge(a,low,(low+high)/2,high);
        }
    }
    //将两个有序区间合并成一个有序区间
    private void merge(int[] a,int p,int q,int r)
    {
        int[] b=new int[r-p+1];
        int s=p;
        int t=q+1;
        int k=0;
        //两个区间以此从小到大比较,比较两个序列最小的元素,取得最小的元素插入到b数组中,以此下去直到其中一个序列全部取完
        while(s<=q && t<=r)
        {
            if(a[s]<a[t])
                b[k++]=a[s++];
            else b[k++]=a[t++];
        }
        while(s<=q)
            b[k++]=a[s++];//将没有取完的元素依次取出
        while(t<=r)
            b[k++]=a[t++];
        for(int i=0;i<b.length;i++)
        {
            a[p+i]=b[i];
        }
    }
    public static void main(String[] args) 
    {
        MergeSort b=new MergeSort();
        int[] a={4,8,3,6,9,7,5,2,1};
        b.mergeSort(a,0,8);
        for(int i=0;i<a.length;i++) 
            System.out.print(a[i]+" ");
    }
}

 

posted @ 2013-10-27 11:06  JMSXH  阅读(110)  评论(0编辑  收藏  举报