top of page

MERGE TWO UNSORTED ARRAYS

Writer's picture: Code CrazeCode Craze



#include <stdio.h>

#define MAX_SIZE 100


void merge_arrays(int arr1[], int arr2[], int m, int n, int arr3[]) {

int i = 0, j = 0, k = 0;

while (i < m && j < n) {

if (arr1[i] < arr2[j]) {

arr3[k++] = arr1[i++];

} else {

arr3[k++] = arr2[j++];

}

}

while (i < m) {

arr3[k++] = arr1[i++];

}

while (j < n) {

arr3[k++] = arr2[j++];

}

}


int main() {

int arr1[MAX_SIZE], arr2[MAX_SIZE], arr3[MAX_SIZE];

int m, n, i;

printf("Enter the size of first array: ");

scanf("%d", &m);

printf("Enter the elements of first array: ");

for (i = 0; i < m; i++) {

scanf("%d", &arr1[i]);

}

printf("Enter the size of second array: ");

scanf("%d", &n);

printf("Enter the elements of second array: ");

for (i = 0; i < n; i++) {

scanf("%d", &arr2[i]);

}

merge_arrays(arr1, arr2, m, n, arr3);

printf("Merged array: ");

for (i = 0; i < m + n; i++) {

printf("%d ", arr3[i]);

}

return 0;

}

8 views0 comments

Recent Posts

See All

Stack Using Queue

A stack can be implemented using two queues in C. The basic idea is to use one queue for enqueue operations and another for dequeue...

Queue Using Stack

A queue can be implemented using two stacks in C. The basic idea is to use one stack for enqueue operations and another for dequeue...

Queue Using Array

#include <stdio.h> #include<stdlib.h> #include<math.h> #define size 5 int queue[size]; int front = -1; int rear = -1; void enque(void);...

Comments


bottom of page