Categories
Academics Computers

C programming code to concatenate 2 sorted arrays in ascending order

Course Details

Field of Study: Computer Science and Engineering
Course Name: C Programming
Course Description: C programming code to concatenate 2 sorted arrays in ascending order

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

void concatenate(int [], int, int [], int, int []);

void main()
{
clrscr();
int a[100], b[100], m, n, c, sorted[200];

printf(“Enter the number of elements of the first array\n”);
scanf(“%d”, &m);

printf(“\nEnter %d sorted integers\n”, m);
for (c = 0; c < m; c++) {
scanf(“%d”, &a[c]);
}

printf(“\nEnter the number of elements of the second array\n”);
scanf(“%d”, &n);

printf(“\nEnter %d sorted integers\n”, n);
for (c = 0; c < n; c++) {
scanf(“%d”, &b[c]);
}

concatenate(a, m, b, n, sorted);

printf(“\nThe Concatenated array:\n”);
printf(“======================\n”);

for (c = 0; c < m + n; c++) {
printf(“%d\n”, sorted[c]);
}

getch();
}

void concatenate(int a[], int m, int b[], int n, int sorted[]) {
int i, j, k;

j = k = 0;

for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (a[j] < b[k]) {
sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Currently you have JavaScript disabled. In order to post comments, please make sure JavaScript and Cookies are enabled, and reload the page. Click here for instructions on how to enable JavaScript in your browser.

Exit mobile version