You are here:

C/merge one arraye's items

Advertisement


Question
Hi
I have a big problem  I don't know what should I do when I want to merge 2 or more items of a array . I mean if we have [ [A] [B] [C] [D] ] and want to have [ [AB][C] [D]]what should we do (which A B C D are int)?please help me

Answer
Hello nasim

I understand you want to merge array B into array A. Most important is to decide if array A has enough space to hold the additional items of array B. If A is declared with a fixed size like
int A[100];
and A is already full, then A must be increased in size. If A is dynamically allocated, like this:
int * A = malloc(100)
then you can use realloc to make A larger.

It is not clear from your question if A and B are sorted. If A and B are sorted and you want the result to be sorted, then it is best to use a third temporary array. Go through A and B, always picking the smallest item from A[i] or B[j] and place that item into the temporary array. Then advance either i or j according to which item was picked. Finally, copy the temporary array back into A and you will have A merged with B and sorted.

I hope this gives you some ideas. If you show me some of your source code, then I can be more sure of what you are trying to do and I can give you more detailed advice.

Best regards
Zlatko  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.