Monday, October 1, 2012

Merging of two sorted arrays

 

Given two sorted arrays A & B where size of A is m & size of B is m+n .  B contains only n number of elements & m empty positions. Sorting should not take any extra memory.

#include<stdio.h>
main()
{
int A[]={1,3,7,10};
int B[7]={2,4,11};
int size_A;
int size_B;
int i;
size_A=sizeof(A)/sizeof(int);
size_B=sizeof(B)/sizeof(int);
size_A--;
size_B--;
int s=size_B;
int B_Elements= (size_B - size_A);
B_Elements--;

while((size_A >=0) && (B_Elements >=0))
{
if( (A[size_A] ) >= (B[B_Elements])){
        B[size_B]=A[size_A];

        printf("\n%d > = %d",A[size_A ] , B[B_Elements ]);
        size_A--;
        size_B--;
}
else
{
printf("\n%d < = %d",A[size_A ] , B[B_Elements ]);
B[size_B] = B[B_Elements];
size_B--;
B_Elements--;
}
}

if ( size_A >=0 ){
    while ( size_A >= 0 ){
B[size_B] = A[size_A];
size_A--;
size_B--;
    }
}
else if ( B_Elements >=0 ) {
    while (B_Elements >=0){
B[size_B] = B[size_B];
    B_Elements--;
    size_B--;
    }
}
else {
printf("Merging done");
}
printf("\n");
for(i=0;i<=s;i++)
printf("%d  ",B[i]);
}

No comments:

Post a Comment