bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / assignment-secondary / assignment-s-15.c

assignment-s-15.c (924B)


      1 /* Write a program to merge two sorted integer arrays to form a single sorted array. */
      2 
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 
      6 void merge(int[], int, int[], int);
      7 
      8 int main()
      9 {
     10     int a[] = {10, 30, 50, 70, 90};
     11     int b[] = {20, 40, 60, 80, 100};
     12     int n1 = sizeof(a) / sizeof(a[0]);
     13     int n2 = sizeof(b) / sizeof(b[0]);
     14     merge(a, n1, b, n2);
     15     return 0;
     16 }
     17 
     18 void merge(int a[], int n1, int b[], int n2)
     19 {
     20     int n = n1 + n2;
     21     int *c = (int *)malloc(n * sizeof(int));
     22     int i, j, k;
     23     i = j = k = 0;
     24     while (i < n1 && j < n2)
     25     {
     26         if (a[i] < b[j])
     27         {
     28             c[k++] = a[i++];
     29         }
     30         else
     31         {
     32             c[k++] = b[j++];
     33         }
     34     }
     35     while (i < n1)
     36     {
     37         c[k++] = a[i++];
     38     }
     39     while (j < n2)
     40     {
     41         c[k++] = b[j++];
     42     }
     43     printf("Merged Array:");
     44     for (i = 0; i < n; i++)
     45     {
     46         printf("  %d", c[i]);
     47     }
     48     free(c);
     49 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror