现在的位置: 首页 > 综合 > 正文

两个有序数组合并为一个有序数组

2013年09月15日 ⁄ 综合 ⁄ 共 1942字 ⁄ 字号 评论关闭

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

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 }

抱歉!评论已关闭.