合并排序

来源:互联网 发布:淘宝客推广网站怎么建 编辑:程序博客网 时间:2024/05/19 22:26
package coding;public class cha04_mergeSort {    public static final int SIZE=20;    static void mergeOne(int a[],int b[],int n,int len){    int i,j,k,s,e;    s=0;    while(s+len<n){        e=s+2*len-1;        if(e>=n){            e=n-1;        }        k=s;        i=s;        j=s+len;        while(i<s+len&&j<=e){            if(a[i]<=a[j]){                b[k++]=a[i++];            }            else{                b[k++]=a[j++];            }        }        while(i<s+len){            b[k++]=a[i++];        }        while(j<=e){            b[k++]=a[j++];        }        s=e+1;    }    if(s<n){        for(;s<n;s++){            b[s]=a[s];        }    }    }    static void mergeSort(int a[],int n){        int h,count,len,f;        count=0;        len =1;        f=0;        int [] p=new int[n];        while(len<n){            if(f==1){                mergeOne(p,a,n,len);            }else{                mergeOne(a,p,n,len);            }            len=len*2;            f=1-f;            count++;            System.out.print("第"+count+"步排序结果:");            for(h=0;h<SIZE;h++){                System.out.print(" "+a[h]);            }            System.out.println();        }        if(f==1){            for(h=0;h<n;h++){                a[h]=p[h];            }        }    }    public static void main(String[] args) {        // TODO Auto-generated method stub        int [] shuzu=new int[SIZE];           int i;           for(i=0;i<SIZE;i++){               shuzu[i]=(int)(100+Math.random()*(100+1));           }           System.out.print("排序前的数组:");           for(i=0;i<SIZE;i++){               System.out.print(shuzu[i]+" ");           }           System.out.println();           mergeSort(shuzu,SIZE);           System.out.print("排序后的数组为:");           for(i=0;i<SIZE;i++){                       System.out.print(shuzu[i]+" ");           }           System.out.println();        }}
0 0