forked from Privanom/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergesort.c
53 lines (47 loc) · 911 Bytes
/
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
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
// function to merge the sub-arrays
void merge(int a[],int low,int mid ,int high)
{
int b[20]; //same size of a[]
int i, j, k;
i = low, j = mid + 1,k = low;
while(i <= mid && j <= high)
{
if(a[i]<=a[j])
b[k++]=a[i++];
else
b[k++]=a[j++]; //copying the elements
}
while (i<=mid)
b[k++]=a[i++];
while
(j<=high) b[k++]=a[j++];
for (k=low;k<=high;k++)
a[k]=b[k];
}
// merge sort function
void mergesort(int a[],int low,int high)
{
int mid;
if(low>=high)
return;
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
// main fucntion
int main()
{
int a[7] = {83, 20, 9, 50, 115, 61, 17};
int n = 7;
mergesort(a, 0, n-1);
printf("\n Sorted numbers are: ");
// function to print the sorted array
int k;
for(k = 0; k < 7; k++)
printf("%d, ",a[k]);
return 0;
}