Monday, February 15, 2016

C Program to merge two array in ascending order.

/*=================================================================================
 **
 **  File Name     : merge2array.c
 **  Creation Date : Mon 15 Feb 2016 06:12:36 AM IST
 **  Last Modified : Mon 15 Feb 2016 06:42:13 AM IST
 **  Compoler      : gcc
 **  Author        : Manoj Kumar Patra, manojpatra.in@gmail.com
 **  Organization  : SCIS, University of Hyderabad, India.
 **
 **===============================================================================*/

#include <stdio.h>
int main()
{
    printf("\n= = = = = = = = = Merge the elements of two array = = = = = = = = =\n");
    int arr1[100], arr2[100], sorted[200], m, n, c;
    int i, j, k;
    j = k = 0;
    printf("\nHow many elements you wanna insert in first array : ");
    scanf("%d", &m);
    printf("Enter %d integers in to first array :\n", m);
    for (c = 0; c < m; c++)
    {   
        scanf("%d", &arr1[c]);      
    }
    printf("\nHow many elements you wanna insert in second array : ");
    scanf("%d", &n);
    printf("Enter %d integers in to second array :\n", n);
    for (c = 0; c < n; c++)
    {   
        scanf("%d", &arr2[c]);   
    }
    for (i = 0; i < m + n;)
    {
        if (j < m && k < n)
        {
            if (arr1[j] < arr2[k])
            {
                sorted[i] = arr1[j];
                j++;
            }
            else
            {
                sorted[i] = arr2[k];
                k++;
            }
            i++;
        }
        else if (j == m)
        {
            for (; i < m + n;)
            {
                sorted[i] = arr2[k];
                k++;
                i++;
            }
        }

        else
        {
            for (; i < m + n;)
            {
                sorted[i] = arr1[j];
                j++;
                i++;
            }
        }
    }
    printf("\nThe elements of merged array are :\n");
    for (c = 0; c < m + n; c++)
    {   
        printf("%d\t", sorted[c]);   
    }
    printf("\n= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n\n");
    return 0;
}

Output:

= = = = = = = = = Merge the elements of two array = = = = = = = = =

How many elements you wanna insert in first array : 3
Enter 3 integers in to first array :
2
4
8

How many elements you wanna insert in second array : 4
Enter 4 integers in to second array :
1
4
6
9

The elements of merged array are :
1    2    4    4    6    8    9   
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

No comments:

Post a Comment