This blog is under construction

Saturday 6 July 2013

C program to merge two arrays and sort the elements

Write a C program to merge two arrays and sort the elements in merged array.


  #include <stdio.h>
  #include <stdlib.h>

  /* merges two input arrays and sorts the elements in merged array */
  void mergeTwoArrays(int *arr1, int *arr2, int *arr3, int n1, int n2) {
        int temp, n, i, j = 0;

        n = n1 + n2;

        /* merging two arrays */
        for (i = 0; i < n1; i++)
                arr3[j++] = arr1[i];

        for (i = 0; i < n2; i++)
                arr3[j++] = arr2[i];

        /* sorting elements in merged array */
        for (i = 0; i < n - 1; i++) {
                temp = arr3[i];
                for (j = i; j < n; j++) {
                        if (temp > arr3[j]) {
                                temp = arr3[j];
                                arr3[j] = arr3[i];
                                arr3[i] = temp;
                        }
                }
        }
        return;
  }

  int main() {
        int *arr1, *arr2, *arr3, n1, n2, i;

        /* get the no of elements for array1 and array2 */
        printf("Number of elements in first array:");
        scanf("%d", &n1);
        printf("Number of elements in second array:");
        scanf("%d", &n2);

        /* allocate memory to store the input elements */
        arr1 = (int *)malloc(sizeof(int) * n1);
        arr2 = (int *)malloc(sizeof(int) * n2);

        /* allocate memory to store the elements of both arrays */
        arr3 = (int *)malloc(sizeof(int) * (n1 + n2));

        /* get the input for array1 */
        printf("Enter the values for Array1:\n");
        for (i = 0; i < n1; i++) {
                printf("Array1[%d]: ", i);
                scanf("%d", &arr1[i]);
        }

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

        /* merging two arrays and sort the element */
        mergeTwoArrays(arr1, arr2, arr3, n1, n2);

        /* print the resultant array */
        printf("\nOutput Array:\n");
        for (i = 0; i < (n1 + n2); i++) {
                printf("%d  ", arr3[i]);
        }
        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Number of elements in first array:3
  Number of elements in second array:3
  Enter the values for Array1:
  Array1[0]: 100
  Array1[1]: 550
  Array1[2]: 220

  Enter the values for Array2:
  Array2[0]: 110
  Array2[1]: 230
  Array2[2]: 150

  Output Array:
  100  110  150  220  230  550  



No comments:

Post a Comment