This blog is under construction

Friday, 26 July 2013

C program to merge two arrays and sort the resultant array

Write a C program to merge two arrays and sort the resultant array.


  #include <stdio.h>
  #define BUFSZ 128
  #define MAX 256

  int main() {
        int arr1[BUFSZ], arr2[BUFSZ], res[MAX];
        int temp, i, j = 0, n1, n2, m;

        /* get the number of entries for the first array */
        printf("Number of entries in the first array:");
        scanf("%d", &n1);

        /* get the number of entries for the second array */
        printf("Number of entries in the second array:");
        scanf("%d", &n2);

        /* get the entries for the first array */
        printf("\nEnter the first array entries:\n");
        for (i = 0; i < n1; i++) {
                printf("Array1[%d]: ", i);
                scanf("%d", &arr1[i]);
        }

        /* get the second array entries */
        printf("\nEnter the second array entries:\n");
        for (i = 0; i < n2; i++) {
                printf("Array2[%d]: ", i);
                scanf("%d", &arr2[i]);
        }

        /* sum of element in first and second array */
        m = n1 + n2;

        /* copying contents of first array to output array */
        for (i = 0; i < n1; i++) {
                res[j++] = arr1[i];
        }

        /* copying the contents of 2nd array to output array */
        for (i = 0; i < n2; i++) {
                res[j++] = arr2[i];
        }

        /* sort the elements in output array */
        for (i = 0; i < m - 1; i++) {
                temp = res[i];
                for (j = i + 1; j < m; j++) {
                        if (temp > res[j]) {
                                temp = res[j];
                                res[j] = res[i];
                                res[i] = temp;
                        }
                }
        }

        /* print the result */
        printf("Resultant array after merge and sort:\n");
        for (i = 0; i < m; i++) {
                printf("%d ", res[i]);
        }

        printf("\n");

        return 0;

  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number of entries in the first array:5
  Number of entries in the second array:4

  Enter the first array entries:
  Array1[0]: 10
  Array1[1]: 20
  Array1[2]: 90
  Array1[3]: 70
  Array1[4]: 60

  Enter the second array entries:
  Array2[0]: 100
  Array2[1]: 95
  Array2[2]: 130
  Array2[3]: 110
  Resultant array after merge:
  10  20  60  70  90  95  100  110  130 


No comments:

Post a Comment