Hi ,

i have to merge two arrays that are already sorted in ascending order .Somehow my code doesn't give the correct output .Can someone please help

include<stdio.h>
#include<conio.h>
void merge(int a[],int b[],int m,int n);
int main(void)
{
    int a[20],b[20];
    int i,n,m;
    printf("\nEnter the number of elements in array A: ");
    scanf("%d",&n);
    printf("\nEnter the elements: ");
    for(i=0;i<n;i++)
                    scanf("%d",&a[i]);
    printf("\nEnter the number of elements in array B: ");
    scanf("%d",&m);
    for(i=0;i<m;i++)
                    scanf("%d",&b[i]);
    printf("\nAfter merging the final array C is ");
    merge(a,b,m,n);
    getch();
    return 0;
}

void merge(int a[],int b[],int m,int n)
{
     int i=0,j=0,k=0,loop;
     int c[40];
     while(i<n && j<m)
     {
            
               if(a[i]<=b[j])
                         c[k++]=a[i++];
               else
                         c[k++]=b[j++];
                         }
      if(i<n)
             c[k++]=a[i++];
      else if(j<m)
             c[k++]=b[j++];
      
      for(loop=0;loop<--k;loop++)
                                 printf("%d\n",c[loop]);
}

Output:
enter the number of elements in array A:4
enter the elements:
1
2
3
4
Enter the number of elements in array B:4
Enter the elements :5
6
7
8
After merging
1
2
Please help!

if(i<n)
             c[k++]=a[i++];
      else if(j<m)
             c[k++]=b[j++];

You need to loop through i and j until i == n and j == m. Note that the if statements are not needed.

while(i<n)
    c[k++]=a[i++];
while(j<m)
 c[k++]=b[j++];

>>for(loop=0;loop<--k;loop++)
Change <-- to just <. You don't want to change the value of k.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.