Sunday 31 August 2014

C Program to merge two sorted arrays

 This program merges two sorted arrays and creates a third array with the values from the two arrays. The final array also is in sorted form. Here first element of list1 and list2 are compared, the lesser value will be assigned to list3. Index of the array, from where the value is taken, ie. i if the array is list1 and j if the array is list2 will be incremented. Index of the third array ie. k will be incremented in both cases. This process will be repeated up to the end of either list1 or list2.

Finally, if list1 or list2  contains any remaining values, it will be copied to list3.


Source Code

#include <stdio.h>
#include <conio.h>

int main() {
    int list1[6]={ 1, 3, 5, 7, 9, 11 };
    int list2[8]={ 2, 4, 6, 8, 10, 12, 13, 14 };
    int list3[14], i, j, k;

    clrscr();


    for (i=0, j=0, k=0; i<6 && j<8 ; k++) {
        /* 

             if ith element of list1 is less than jth element of list2, takes value from list1
             otherwise takes value from list2 and assigns to list3.
      */
        if (list1[i] < list2[j]) {
            list3[k] = list1[i];
            i++;
        }
        else {
            list3[k] = list2[j];
            j++;
        }

    }

  /* If list1 has remaining values assigns them to list3*/

    for (; i<6 ;i++, k++) {
        list3[k] = list1[i];
    }


  /* If list2 has remaining values assigns them to list3 */
     for (; j<8 ;j++, k++) {
        list3[k] = list2[j];
    }


    printf("\n\nList 1\n\n");
    for (i=0; i<6 ; i++) {
        printf ("%d ", list1[i]);
    }

    printf("\n\nList 2\n\n");
    for (i=0; i<8 ; i++) {
        printf ("%d ", list2[i]);
    }

    printf("\n\nList 3\n\n");
    for (i=0; i<14 ; i++) {
        printf ("%d ", list3[i]);
    }

    printf("\n\nPress any key to continue...");
    getch();

    return 0;
}


Output



No comments:

Post a Comment