Two Pointer Approach to Merge Sorted Arrays in C
C
Medium
3 views
Problem Description
Merging two sorted arrays into a third sorted array - two pointer approach followed by comparison and selection logic?
Official Solution
#include <stdio.h>
int main() {
int a[] = {1, 3, 5, 7};
int b[] = {2, 4, 6, 8};
int n = 4, m = 4;
int c[n + m];
int i = 0, j = 0, k = 0;
// Merge using two pointers
while (i < n && j < m) {
if (a[i] < b[j]) {
c[k++] = a[i++];
} else {
c[k++] = b[j++];
}
}
// Copy remaining elements of array a
while (i < n) {
c[k++] = a[i++];
}
// Copy remaining elements of array b
while (j < m) {
c[k++] = b[j++];
}
// Print merged array
printf("Merged sorted array:n");
for (i = 0; i < n + m; i++) {
printf("%d ", c[i]);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!