-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.c
More file actions
110 lines (93 loc) · 2.16 KB
/
MergeSort.c
File metadata and controls
110 lines (93 loc) · 2.16 KB
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
#include <stdio.h>
#include <stdlib.h>
//For the array size input
int arraySize(){
int s;
printf("Input the array size: ");
scanf("%d", &s);
return s;
}
//For the array input
void arrayInput(int s, int x[]){
printf("Input the array: ");
for(int j = 0; j < s; j++){
scanf("%d", &x[j]);
}
}
//The function to merge the array halves
void merge(int a[], int s, int m, int e){
//Creating the array halces to sort
int s1 = m - s + 1;
int s2 = e - m;
int *b1 = (int*)calloc(s1, sizeof(int));
int *b2 = (int*)calloc(s2, sizeof(int));
//Demerging the array halves
for(int j = 0; j < s1; j++){
b1[j] = a[s + j];
}
for(int j = 0; j < s2; j++){
b2[j] = a[m + 1 + j];
}
//Merging the array halves
int j = 0, k = 0, v = s;
while(j < s1 && k < s2){
if(b1[j] < b2[k]){
a[v] = b1[j];
j++;
}
else{
a[v] = b2[k];
k++;
}
v++;
}
//Filling up the remaining array
while(j < s1){
a[v] = b1[j];
j++;
v++;
}
while(k < s2){
a[v] = b2[k];
k++;
v++;
}
//Freeing the allocated memory
free(b1);
free(b2);
}
//The recursive Merge Sorting algorithm
void mergeSort(int a[], int s, int e){
if(s < e){
//Finding the mid point
int m = s + (e - s)/2;
//Sorting the arrays recursively using merge sort
mergeSort(a, s, m);
mergeSort(a, m+1, e);
//Sorting and merging the array halves
merge(a, s, m, e);
}
return;
}
//For printing out the array's elements on the screen
void arrayOutput(int s, int a[]){
printf("The new array is: ");
for(int k = 0; k < s; k++){
printf("%d ", a[k]);
}
printf("\n");
}
int main()
{
//Taking input
int s = arraySize();
int *a = (int *)calloc(s, sizeof(int));
arrayInput(s, a);
//Sorting using mergeSort
mergeSort(a, 0, s - 1);
//Printing the output
arrayOutput(s, a);
//Freeing the allocated memory
free(a);
return 0;
}