-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort Final
61 lines (61 loc) · 910 Bytes
/
MergeSort Final
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
#include <stdio.h>
void mergesort(int a[],int beg,int end);
void merge(int a[],int beg,int mid,int end);
int i,j,k,n;
int a[10],temp[10];
void main() {
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the elements: ");
for(i=0;i<n;i++) {
scanf("%d", &a[i]);
}
printf("The sorted array is : ");
mergesort(a,0,n-1);
for (i=0;i<n;i++) {
printf("%d ",a[i]);
}
printf("\n");
}
void mergesort(int a[], int beg, int end) {
if (beg<end) {
int mid=(beg+end)/2;
mergesort(a,beg,mid);
mergesort(a,mid+1,end);
merge(a,beg,mid,end);
}
}
void merge(int a[],int beg,int mid,int end)
{
int i=beg;
int j=mid+1;
int index=0;
while (i<=mid && j<=end) {
if (a[i]<a[j]) {
temp[index]=a[i];
i++;
}
else {
temp[index]=a[j];
j++;
}
index++;
}
while (i<=mid) {
temp[index]=a[i];
i++;
index++;
}
while (j<=end) {
temp[index]=a[j];
j++;
index++;
}
k=beg;
index = 0;
while (k<=end) {
a[k]=temp[index];
k++;
index++;
}
}