forked from Shreyashi14/DAA-AIML-Hons.-B1-B2-B3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge.c
78 lines (64 loc) · 1.32 KB
/
Merge.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
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
void merge(int arr[], int left[], int right[], int left_size, int right_size)
{
int i = 0, j = 0, k = 0;
while (i < left_size && j < right_size)
{
if (left[i] <= right[j])
{
arr[k++] = left[i++];
}
else
{
arr[k++] = right[j++];
}
}
while (i < left_size)
{
arr[k++] = left[i++];
}
while (j < right_size)
{
arr[k++] = right[j++];
}
}
void mergeSort(int arr[], int n)
{
if (n <= 1)
{
return;
}
int mid = n / 2;
int left[mid];
int right[n - mid];
for (int i = 0; i < mid; i++)
{
left[i] = arr[i];
}
for (int i = mid; i < n; i++)
{
right[i - mid] = arr[i];
}
mergeSort(left, mid);
mergeSort(right, n - mid);
merge(arr, left, right, mid, n - mid);
}
int main()
{
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
mergeSort(arr, n);
printf("Sorted array:\n");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}