forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.c
99 lines (81 loc) · 2.13 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
// MERGE SORT IN C
#include<stdio.h>
void main()
{
int arraySize , index;
printf("Please enter the size of the array\n");
scanf("%d",&arraySize);
int arr[arraySize];
printf("Please enter the elements to sort\n");
for(index=0 ; index<arraySize ; index++)
{
scanf("%d",&arr[index]);// You would now fill the array with the numbers you want to sort
}
// Now the lower bound and upper bound values would be defined
int lower_bound =0;
int upper_bound = arraySize-1;
// we pass three parameters to the mergeSort function
mergeSort(arr,lower_bound, upper_bound);
printf("SORTED ARRAY\n");
for(index=0 ; index<arraySize ; index++)
{
printf("%d\t",arr[index]);
}
}
int mergeSort(int arr[],int lower_bound, int upper_bound)
{
// We use recursion to divide the array
if(lower_bound<upper_bound)
{
int mid = (lower_bound+upper_bound)/2;
mergeSort(arr,lower_bound,mid);
mergeSort(arr,mid+1,upper_bound);
// Now we use merge function to join the array in a sorted manner
merge(arr , lower_bound , mid , upper_bound );
}
}
int merge(int arr[],int lower_bound , int mid , int upper_bound )
{
int variable_a = lower_bound ;
int variable_b = mid+1;
int variable_c = lower_bound;
int size = upper_bound+1 ;
int arr_new[size]; // we create a new array by arr_new
while(variable_a<=mid && variable_b<=upper_bound )
{
if(arr[variable_a]<=arr[variable_b])
{
arr_new[variable_c] = arr[variable_a];
variable_a++;
}
else
{
arr_new[variable_c] = arr[variable_b];
variable_b++ ;
}
variable_c++;
}
if(variable_a>mid)
{
while(variable_b<=upper_bound)
{
arr_new[variable_c] = arr[variable_b];
variable_b++ ;
variable_c++;
}
}
else
{
while(variable_a<= mid )
{
arr_new[variable_c] = arr[variable_a];
variable_a++ ;
variable_c++ ;
}
}
for(variable_c=lower_bound; variable_c<=upper_bound ; variable_c++)
// Copying the sorted values from array_new to arr
{
arr[variable_c] = arr_new[variable_c];
}
}