java版本:
实例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public class Merge {
//合并有序数组
public static void mergeSort( int a[], int b[], int c[]) {
int n = a.length, m = b.length;
int i, j, k;
i = j = k = 0 ;
while (i < n && j < m) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
while (i < n)
c[k++] = a[i++];
while (j < m)
c[k++] = b[j++];
}
//打印数组中的元素
public static void printArr( int a[]) {
for ( int i = 0 ; i < a.length; i++) {
System.out.print(a[i] + "\t" );
}
}
public static void main(String[] args) {
System.out.println( "Hello World!" );
int [] a = new int [] { 1 , 2 , 5 , 6 };
int [] b = new int [] { 3 , 8 , 9 , 10 };
int c[] = new int [ 8 ];
mergeSort(a, b, c);
printArr(c);
}
}
|
输出结果:
1
|
1 2 3 5 6 8 9 10
|
C语言版
实现代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
#include <stdio.h>
// 打印数组a
void printArr( int a[], int n){
for ( int i = 0; i < n; ++i)
{
printf ( "%d\t" ,a[i]);
}
printf ( "\n" );
}
//合并有序数组
void mergeArray( int a[], int n, int b[], int m, int c[]){
int i, j, k;
i = j = k = 0;
while (i <n && j<m)
{
if (a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
while (i < n)
c[k++] = a[i++];
while (j < m)
c[k++] = b[j++];
}
int main(){
int a[3]={2,3,6};
int b[2]={1,5};
int c[5]={};
mergeArray(a,3,b,2,c);
printArr(c,5);
}
|
输出结果:
1
2
|
yaopans-MacBook-Pro:algorithm yaopan$ ./a.out
1 2 3 5 6
|
以上就是java与C语言实现合并有序数组的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://blog.csdn.net/napoay/article/details/50130749