-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.c
76 lines (63 loc) · 1.19 KB
/
merge_sort.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
#include <stdio.h>
void merge(int arr[], int lb, int mid, int ub,int N)
{
int i= lb;
int j= mid+1;
int k=lb;
int b[N];
while(i<=mid && j<=ub){
if(arr[i]<=arr[j]){
b[k]=arr[i];
i++;
}
else{
b[k]=arr[j];
j++;
}
k++;
}
if(i>mid){
while(j<=ub){
b[k]=arr[j];
j++;
k++;
}
}
else{
while(i<=mid){
b[k]=arr[i];
i++;
k++;
}
}
for(k=lb;k<=ub;k++){
arr[k]=b[k];
}
}
void mergeSort(int arr[], int lb, int ub,int N)
{
if(lb < ub){
int mid = (lb+ub)/2;
mergeSort(arr, lb, mid,N);
mergeSort(arr,mid+1, ub,N);
merge(arr,lb,mid,ub,N);
}
}
int main()
{
int N;
printf("Enter Array Size:");
scanf("%d",&N);
int arr[N];
printf ("Enter Array Elements:\n");
for(int I=0;I<N;I++){
scanf("%d",&arr[I]);
}
int lb=0;
int ub=N-1;
mergeSort(arr, lb, ub,N);
printf("Sorted array is:\n");
for (int i = 0; i < N; i++){
printf("%d ", arr[i]);
}
}