-
Notifications
You must be signed in to change notification settings - Fork 1
/
MergeSortRecursive.c
67 lines (49 loc) · 1.03 KB
/
MergeSortRecursive.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
#include<stdio.h>
#define NUMLETS 50
void merge(int a[],int l1,int u1, int l2, int u2);
void mergesort(int a[],int i,int j);
int main()
{
int a[NUMLETS],n,i;
printf("Enter the no of the elements : ");
scanf("%d",&n);
printf("Enter the elements of the array : ");
for(i=0;i<n;i++)
scanf("%d\n",&a[i]);
mergesort(a,0,n-1);
printf("The Sorted elements of the array is : ");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}
void mergesort(int a[], int i, int j)
{
int mid;
if(i<j)
{
mid = (i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}
void merge(int a[], int l1, int u1, int l2, int u2)
{
int aux[NUMLETS];
int i,j,k;
i=l1;
j=l2;
k=0;
while(i<=u1 && j<=u2)
{
if(a[i]<a[j])
aux[k++]=a[i++];
else
aux[k++]=a[j++];
}
while(i<=u1)
aux[k++]=a[i++];
while(j<=u2)
aux[k++]=a[j++];
for(i=l1,j=0;i<=u2;i++,j++)
a[i]=aux[j];
}