自己用java写的归并排序 (参考的是严版的数据结构)

import java.util.*;

public class MergeSort {

    /**
     * @param args
     */
    static void  mergeSort(int [] a,int [] temp,int left,int right)
    {
       
        if (left==right)
            temp[left]=a[left];
        else
        {
            int  temp2[]=new int[] {0,0,0,0,0,0,0,0,0,0};
            int middle=(left+right)/2;
            mergeSort(a,temp2,left,middle);
            mergeSort(a,temp2,middle+1,right);
            merge(temp2,temp,left,middle,right);
           
        }
    }

    static void merge(int[] temp2,int[] temp,int left,int middle,int right)
    {
        int k,j;
        for(k=left,j=middle+1;left<=middle&&j<=right;++k)
        {
            if(temp2[left]<temp2[j])
                temp[k]=temp2[left++];
            else
                temp[k]=temp2[j++];
        }
        /*    if(left<=middle&&middle<=right-1)
            {
                if(temp2[left]<temp2[middle+1])
                {   
                    temp[count]=temp2[left];
                    left++;
                else
                {
                    temp[count]=temp2[middle+1];
                    middle++;
                }
                count++;
            }*///我错误点在于:1是middle是自己增加的,没有将j=middle+1,导致会出现问题。
              //第二个问题是好多自加操作实际上是可以用left++可以放到运算的内部。
       
        while(left<=middle)
            temp[k++]=temp2[left++];
        while(j<=right)
            temp[k++]=temp2[j++];
        //代码要美观,哈
               
    }
   
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int  a[]=new int[] {9,2,4,5,8,0,1,3,7,6};
        for(int i=0;i<10;i++)
        {
            System.out.printf("%d ",a[i]);
        }
        int  temp[]=new int[] {0,0,0,0,0,0,0,0,0,0};
        mergeSort(a,temp,0,9);
        System.out.println("排序后的结果是");
        for(int i=0;i<10;i++)
        {
            System.out.printf("%d ",temp[i]);
        }
   
        Scanner in =new Scanner(System.in);
        in.nextInt();
       

    }

}

posted @ 2011-06-21 11:27  thinking and coding  阅读(179)  评论(0编辑  收藏  举报