-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.c
83 lines (73 loc) · 1.3 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
#include <stdio.h>
void mergeSort(int[],int,int);
void merge(int[],int,int,int);
void display(int arr[], int size){
int i;
for(i = 0; i < size; i++){
printf("%d ",arr[i]);
}
printf("\n");
}
void main()
{
int a[10]= {11, 9, 6, 19, 33, 64, 15, 75, 67, 88};
int i;
int size = sizeof(a)/sizeof(a[0]);
display(a, size);
mergeSort(a,0,size-1);
display(a, size);
}
void mergeSort(int a[], int strt, int end)
{
int mid;
if(strt<end)
{
mid = (strt+end)/2;
mergeSort(a,strt,mid);
mergeSort(a,mid+1,end);
merge(a,strt,mid,end);
}
}
void merge(int a[], int strt, int mid, int end)
{
int i=strt,j=mid+1,p,index = strt;
int temp[10];
while(i<=mid && j<=end)
{
if(a[i]<a[j])
{
temp[index] = a[i];
i = i+1;
}
else
{
temp[index] = a[j];
j = j+1;
}
index++;
}
if(i>mid)
{
while(j<=end)
{
temp[index] = a[j];
index++;
j++;
}
}
else
{
while(i<=mid)
{
temp[index] = a[i];
index++;
i++;
}
}
p = strt;
while(p<index)
{
a[p]=temp[p];
p++;
}
}