逆龙七步

导航

排序小结(java版)

一、归并排序


package org.lxh.demo08.b;


class Sort
{
    private int[] a;
    private int n;
    Sort(int n)
    {
        a=new int[n];
    }
    Sort(int[] a,int n)
    {
        this.n=n;
        this.a=new int[n];
        this.a=a;
    }
    public void print()
    {
        for(int i=0;i<n;i++)
            System.out.print(a[i]+" ");
    }
    //合并a[u,...,v-1]和[v,...,t]
    public void merge(int a[], int[] des,int u,int v,int t)
    {
        int i=u;
        int j=v;
        int k=u;
        while(i<=v-1&&j<=t)
        {
            if(a[i]<=a[j])
                des[k++]=a[i++];
            else
                des[k++]=a[j++];            
        }
        while(i<=v-1)
            des[k++]=a[i++];
        while(j<=t)
            des[k++]=a[j++];
    }
    public void onepass(int a[],int[] des,int s)
    {
        int u=0;
        int v=s;
        int t=2*s-1;
        while(n-u>=2*s)
        {
            merge(a,des,u,v,t);
            u+=2*s;
            v+=2*s;
            t+=2*s;
        }
        if(n-u>s)
            merge(a,des,u,v,n-1);
        else
        {
            System.arraycopy(a,u,des,u,n-u);
    /*        for(;u<n;u++)
            {
                des[u]=a[u];                
            }*/
        }
    }
    public void mergesort()
    {
        int s=1;
        int[] des=new int[n];
        while(s<n)
        {
            onepass(a,des,s);
            s=2*s;
            if(s>=n)
            {
                System.arraycopy(des,0,a,0,n);
            }
            else
            {
                onepass(des,a,s);
                s=2*s;
            }
        }
        des=null;
    }
}
public class RunnableTest
{
    public static void main(String args[]) 
    {
        int[] a={5,8,2,7,1,0,6};
        Sort b=new Sort(a,7);
        b.mergesort();
        b.print();
    }
}

 

posted on 2014-04-04 12:44  逆龙七步  阅读(171)  评论(0编辑  收藏  举报