java实现两个有序数组的合并

思想:先依次比较两个数组,按照小的就传入新的数组。当这次比较完之后可能有一个数组的长度很长,留下一些数组,然后在新数组的末尾插入即可。

代码:

 

复制代码
 1  class  ArraySort
 2  {
 3       // 两个有序数组的合并函数
 4       public   static   int [] MergeList( int  a[], int  b[])
 5      {
 6           int  result[];  
 7           if (checkSort(a)  &&  checkSort(b))   // 检查传入的数组是否是有序的
 8          {
 9              result  =   new   int [a.length + b.length];
10              
11               int  i = 0 ,j = 0 ,k = 0 ;    // i:用于标示a数组    j:用来标示b数组  k:用来标示传入的数组
12 
13               while (i < a.length  &&  j < b.length)
14                   if (a[i]  <=  b[j]) {
15                      result[k ++ =  a[i ++ ];
16                  } else {
17                      result[k ++ =  b[j ++ ];
18                  }
19 
20               /*  后面连个while循环是用来保证两个数组比较完之后剩下的一个数组里的元素能顺利传入  */
21               while (i  <  a.length) 
22                  result[k ++ =  a[i ++ ];
23               while (j  <  b.length)
24                  result[k ++ =  b[j ++ ];
25              
26               return  result;
27          }
28           else  
29          {
30              System.out.print( " 非有序数组,不可排序! " );
31               return   null ;
32          }
33      }
34      
35       // 检查数组是否是顺序存储的
36       public   static   boolean  checkSort( int  a[])
37      {
38           boolean  change  =   true ;   // 这个标志位是一种优化程序的方法,可以看看我写的冒泡排序优化就会明白了
39           for ( int  i = 0 ; i < a.length - 1   &&  change; i ++ )
40          {
41               for ( int  j = i + 1 ; j < a.length; j ++ )
42                   if (a[j - 1 >  a[j])
43                       return   false ;
44                   else  change  =   false ;
45          }
46           return   true ;        
47      }
48      
49       //  打印函数
50       public   static   void  print( int  b[])
51      {
52            for ( int  i = 0 ; i < b.length ; i ++ )
53           {
54               System.out.print(b[i]  +  (i % 10   == 9   ?   " \n " : " \t " ));
55           }
56      }
57      
58       public   static   void  main(String args[])
59      {
60           int  a[] = { 1 , 2 , 2 , 3 , 5 , 6 , 7 , 7 };
61           int  b[] = { 1 , 2 , 4 , 5 , 8 , 8 , 9 , 10 , 11 , 12 , 12 , 13 , 14 };
62           int  c[] =  MergeList(a,b);
63           if (c != null )
64          print(c);
65           else
66              System.out.println( "" );
67      }
68  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值