forked from Vishal-Aggarwal0305/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.c
73 lines (68 loc) · 1.29 KB
/
MergeSort.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
#include <stdio.h>
#include <stdlib.h>
int c;
void mergeSort(int[], int, int);
void merge(int[], int, int, int);
int main()
{
int a[50], n, i;
printf("Enter the elements: ");
scanf("%d", &n);
printf("Enter elements : ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("before sort\n");
mergeSort(a, 0, n - 1);
printf("after sort\n");
printf("\nSorted array is \n");
for (i = 0; i < n; i++)
{
printf("%d\t", a[i]);
}
printf("\nNumer of exchanges: %d", c);
return 0;
}
void merge(int A[], int beg, int mid, int end)
{
int temp[35], i, j, k;
k = 0;
i = beg;
j = mid + 1;
while (i <= mid && j <= end)
{
if (A[i] < A[j])
{
temp[k++] = A[i++];
c++;
}
else
{
temp[k++] = A[j++];
c++;
}
}
while (i <= mid)
{
temp[k++] = A[i++];
c++;
}
while (j <= end)
{
temp[k++] = A[j++];
c++;
}
for (i = end; i >= beg; i--)
{
A[i] = temp[--k];
}
}
void mergeSort(int a[], int BEG, int END)
{
if (BEG < END)
{
int MID = (BEG + MID) / 2;
mergeSort(a, BEG, MID);
mergeSort(a, MID + 1, END);
merge(a, BEG, MID, END);
}
}