将两个已排好序的数组,合并成一个新的排好序的数组

 1 /**
 2  * 
 3  * @author hanxin
 4  * 标题:将两个已排好序的数组,合并成一个新的排好序的数组
 5  *
 6  */
 7 public class Merge {
 8 
 9     /**
10      * @param args
11      */
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14         ArrayList<Integer> C=mergeAB(A, B);
15         System.out.println(C.size());
16         for(int i=0;i<C.size();i++)
17         {
18             System.out.println(C.get(i));
19         }
20     }
21     public static int[]A={2,3,6,9,12};
22     public static int[]B={3,4,6,8,10};
23     public static ArrayList<Integer> mergeAB(int []A,int []B)
24     {
25         ArrayList<Integer> C=new ArrayList<Integer>();
26         int i=0,j=0;
27         while(i<A.length && j<B.length)
28         {
29             if(A[i]<B[j])//当A[4]与B[4]比较时
30             {
31                 C.add(A[i]);
32                 System.out.println("C["+i+"]="+A[i]+"  i="+i);
33                 i++;
34             }
35             else
36             {
37                 C.add(B[j]);
38                 System.out.println("C["+j+"]="+B[j]+"  j="+j);
39                 j++;//执行了这一句
40             }
41         }
42         if(i==A.length)//是A.length而不是A.length-1,调试时发现这个错误
43         {
44             while(j<B.length)
45             {
46                 C.add(B[j]);
47                 System.out.println("C["+j+"]="+B[j]+"  j="+j);
48                 j++;
49             }
50         }
51         if(j==B.length)
52         {
53             while(i<A.length)
54             {
55                 C.add(A[i]);
56                 System.out.println("C["+i+"]="+A[i]+"  i="+i);
57                 i++;
58             }
59         }        
60         return C;
61     }    
62 }
View Code

 

调试时用的代码没有删去,在使用时,大家可以删去。
如果代码有问题,请指出,谢谢。

 

 

小小程序员--一直很安静的我。

 

 

posted on 2013-08-26 15:16  一直很安静的我  阅读(614)  评论(0编辑  收藏  举报

导航