|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Array Merging
Overview
Write a program to merge two arrays
Directions
For example, consider two arrays A and B.
A = {10, 25, 35, 40, 55}
B = {15, 30, 5, 20, 45, 65}
The merged array should be another array C with elements {5, 10, 15, 20, 25, 30, 35, 40, 45, 55, 65}. The resultant merged array should contain all the elements of A and B in sorted order. This doesn’t mean that you can two copy two arrays to the third array and sort the resultant array. However, you have to merge the contents of the two arrays by taking individual values of the two arrays one by one and insert it into the resultant array in the appropriate position, so that it becomes sorted right after merging.
#include <stdio.h>
int main(void)
{
int A[] = {10, 25, 35, 40, 55} , B[] = {15, 30, 5, 20, 45, 65} ;
int C[100] , a , b , c , i , j , k , m ;
for(a = sizeof(A) / 4 , c = 0 ; c < a ; c ++) C[c] = A[c] ;
for(b = sizeof(B) / 4 , i = 0 ; i < b ; i ++) {
for(j = 0 ; j < c && C[j] <= B[i] ; j ++) ;
if(j < c) {
for(k = c ; k > j ; k --) C[k] = C[k - 1] ;
C[j] = B[i] ;
} else {
C[c] = B[i] ;
}
c ++ ;
}
printf("%d" , C[0]) ;
for(k = 1 ; k < c ; k ++) printf("\t%d" , C[k]) ;
printf("\n") ;
}
编译、运行实况 D:\0002.Exercise\C>g++ -o x x.c
D:\0002.Exercise\C>x
5 10 15 20 25 30 35 40 45 55
65
D:\0002.Exercise\C>
|
|