-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.c
68 lines (58 loc) · 1.19 KB
/
16.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 16. Merge and Sort Elements of 2 different Arrays
#include <stdio.h>
#include <malloc.h>
void sort(int *arr, int n) {
for (int i = 0; i < n-1; i++) {
int pos = i;
for (int j = i; j < n; j++) {
if (arr[pos] > arr[j]) {
pos = j;
}
}
int temp = arr[pos];
arr[pos] = arr[i];
arr[i] = temp;
}
}
int *merge(int *arr1, int *arr2, int n, int m) {
int *merged = (int *)malloc(sizeof(int)*(n + m));
if (merged == NULL) {
printf("Memory could not be allocated!\n");
}
int i = 0, j = 0, k = 0;
while (i < n && j < m) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < n) {
merged[k++] = arr1[i++];
}
while (j < m) {
merged[k++] = arr2[j++];
}
return merged;
}
int main() {
int n, m;
printf("SIZE 1: ");
scanf("%d", &n);
int arr1[n];
printf("ARRAY 1: ");
for (int i = 0; i < n; i++)
scanf("%d", &arr1[i]);
printf("SIZE 2: ");
scanf("%d", &m);
int arr2[m];
printf("ARRAY 2: ");
for (int i = 0; i < m; i++)
scanf("%d", &arr2[i]);
sort(arr1, n);
sort(arr2, m);
int *merged = merge(arr1, arr2, n, m);
printf("\nSORTED AND MERGED ARRAY: ");
for (int i = 0; i < n+m; i++)
printf("%d ", merged[i]);
}