-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergesort.c
121 lines (76 loc) · 2.65 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//By Aadhaar koul
//Cse - A1 - 2020a1r040
//Mergesort in c language
//Comments have been Implemented for better understanding
//( Authentic Code ) - No plagiarism Done
//*All rights Reserved with the owner
#include <stdio.h>
// function to sort the subsection a[i .. j] of the array a[]
void merge_sort(int i, int j, int a[], int aux[]) {
if (j <= i) {
return;
// the subsection is empty or a single element
}
int mid = (i + j) / 2;
// left sub-array is a[i .. mid]
// right sub-array is a[mid + 1 .. j]
merge_sort(i, mid, a, aux);
// sort the left sub-array recursively
merge_sort(mid + 1, j, a, aux);
// sort the right sub-array recursively
int pointer_left = i;
// pointer_left points to the beginning of the left sub-array
int pointer_right = mid + 1;
// pointer_right points to the beginning of the right sub-array
int k;
// k is the loop counter
// we loop from i to j to fill each element of the final merged array
for (k = i; k <= j; k++) {
if (pointer_left == mid + 1) {
// left pointer has reached the limit
aux[k] = a[pointer_right];
pointer_right++;
} else if (pointer_right == j + 1) {
// right pointer has reached the limit
aux[k] = a[pointer_left];
pointer_left++;
} else if (a[pointer_left] < a[pointer_right]) {
// pointer left points to smaller element
aux[k] = a[pointer_left];
pointer_left++;
} else {
// pointer right points to smaller element
aux[k] = a[pointer_right];
pointer_right++;
}
}
for (k = i; k <= j; k++) {
// copy the elements from aux[] to a[]
a[k] = aux[k];
}
}
int main() {
//Declaring the arrays and Integers
int a[100], aux[100], n, i, d, swap;
//Taking inputs of the Number of elements
printf("Enter number of elements you want to sort.\n");
scanf("%d", &n);
//Storing the Elements
printf("Enter the elements\n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Unsorted array :\n");
for (i = 0; i < n; ++i)
{
printf("| %d |", a[i]);
}
printf("\n");
//Calling the mergesort function
merge_sort(0, n - 1, a, aux);
//Printing the sorted arrayy
printf("\nSorted array:\n");
for (int i = 0; i < n; i++)
printf("| %d |", a[i]);
return 0;
//End
}