forked from harsimrans/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.c
89 lines (83 loc) · 1.4 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
89
/*****************************************
*
* Merge Sort algorithm
*
* Mohit Goyal
*
* Takes an array input and outputs the
* sorted array using merge sort algo.
*
******************************************/
#include <stdio.h>
void mergelist(int*,int,int,int,int);
void splitlist(int*,int,int,int);
void mergesort(int*,int);
int main()
{
int size=10,a[10],i; // array a of size 10
printf("\nEnter the values: \n");
for(i=0;i<size;i++)
{
scanf("%d",a+i); // input the elements to array
}
printf("\n\nBefore Sorting\n");
for(i=0;i<size;i++)
{
printf(" %d",a[i]);
}
mergesort(a,10);
printf("\n\nAfter Sorting\n");
for(i=0;i<size;i++)
{
printf(" %d",a[i]);
}
return 0;
}
void mergesort(int *a,int size)
{
splitlist(a,0,size-1,size);
}
void splitlist(int *a,int start,int end,int size)
{
int mid,i;
if(start == end)
return;
mid = (start + end)/2;
splitlist(a,start,mid,size);
splitlist(a,mid+1,end,size);
mergelist(a,start,mid,end,size);
}
void mergelist(int *a,int start,int mid,int end,int size)
{
int i = start,begin = start,m = mid + 1,k,b[size];
while(start <= mid && m <= end)
{
if(a[start] < a[m])
{
b[i] = a[start];
start++;
i++;
}
else
{
b[i] = a[m];
m++;
i++;
}
}
if(m > end)
{
for(k=start;k<=mid;k++)
b[i++] = a[k];
}
else
{
for(k = m;k<=end;k++)
b[i++] = a[k];
}
for(i=begin;i<=end;i++)
{
a[i] = b[i];
}
}