-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.c
88 lines (64 loc) · 1.46 KB
/
merge_sort.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
79
80
81
82
83
84
85
86
87
88
// Worst-case performance O(n log n)
// Best-case performance O(n log n) typical, O(n) natural variant
// Average performance O(n log n)
#include<stdio.h>
void MergeSort(int *a, int l, int r);
void Merge(int *a, int i1, int j1, int i2, int j2);
int main() {
int i, n, array[50];
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("\nEnter the numbers:\n");
for(i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
MergeSort(array, 0, n-1);
printf("\nSorted Array\n");
for(i = 0; i < n; i++) {
printf("%d ", array[i]);
}
return 0;
}
void MergeSort(int *a, int low, int high) {
int mid;
if(low < high) {
mid = (low + high)/2;
MergeSort(a, low, mid); // Left array.
MergeSort(a, mid + 1, high); // Right array.
Merge(a, low, mid, mid + 1, high);
}
}
void Merge(int *a, int i1, int j1, int i2, int j2) {
int temp[50]; // Temporary array used for merging.
int i = i1; // Beginning of the left array.
int j = i2; // Beginning of the right array.
int k = 0;
while (i<=j1 && j<=j2) {
if(a[i] < a[j]) {
temp[k] = a[i];
k++;
i++;
}
else {
temp[k] = a[j];
k++;
j++;
}
}
// Copying remaining elements from the left array.
while( i <= j1) {
temp[k] = a[i];
i++;
k++;
}
// Copying remaining elements from the right array.
while( j <= j2) {
temp[k] = a[j];
j++;
k++;
}
// Copying elements from temporary array to main array.
for(i = i1, j = 0; i <= j2; i++, j++) {
a[i] = temp[j];
}
}