-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMergeSort
More file actions
56 lines (56 loc) · 988 Bytes
/
MergeSort
File metadata and controls
56 lines (56 loc) · 988 Bytes
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
# include <stdio.h>
void merge_sort(int a[],int low,int high);
void merge(int a[],int low, int mid, int high);
int main(){
int arr[1000],n,i;
printf("\n Enter the number of elements to be sorted");
scanf("%d",&n);
printf("\n Enter the elements");
for(i=0;i<n;i++){
scanf("%d",&arr[i]);
}
printf("\n The sorted array is");
merge_sort(arr,0,n-1);
for(i=0;i<n;i++){
printf("\n %d",arr[i]);
}
return 0;
}
void merge_sort(int a[],int low,int high){
int mid;
mid = (low+high)/2;
if(low!=high){
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merge(a,low,mid,high);
}
}
void merge(int a[],int low, int mid, int high){
int f=low,s=mid+1,t=low,temp[1000],i,j;
while(f<=mid && s<=high){
if(a[f]<=a[s]){
temp[t]=a[f];
f=f+1;
}
else{
temp[t]=a[s];
s=s+1;
}
t=t+1;
}
if(f>mid){
for(i=s;i<=high;i++){
temp[t]=a[i];
t=t+1;
}
}
else{
for(i=f;i<=mid;i++){
temp[t]=a[i];
t=t+1;
}
}
for(j=low;j<=high;j++){
a[j]=temp[j];
}
}