-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMergeSort.c
More file actions
137 lines (111 loc) · 2.07 KB
/
MergeSort.c
File metadata and controls
137 lines (111 loc) · 2.07 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<stdio.h>
/*int a[14] = { 14,19,5,6,3,235,2,34,42,23,454,4,657,5 };
void mergesort(int a[],int s,int e)
{
if(s>=e)
{
return;
}
int mid=(s+e)/2;
mergesort(a,s,mid);
mergesort(a,mid+1,e);
merge(a,s,e);
}
void merge(int *a,int s,int e)
{
int mid=(s+e)/2;
int i=s;
int j=mid+1;
int k=s;
int temp[100];
while(s<=mid && j<=e)
{
if(a[i]>a[j])
{
temp[k++]=a[j++];
}
else
{
temp[k++]=a[i++];
}
}
while(i<=mid)
{
temp[k++]=a[i++];
}
while(j<=e)
{
temp[k++]=a[j++];
}
for(i=s;i<=e;i++)
{
a[i]=temp[i];
}
}
void main()
{
int i;
for(i=0;i<14;i++)
{
printf("%d\n",a[i]);
}
mergesort(a,0,13);
for(i=0;i<14;i++)
{
printf("%d\n",a[i]);
}
}
*/
void merge(int *a,int s,int e){
int mid = (s+e)/2;
int i = s;
int j = mid+1;
int k = s;
int temp[100];
while(i<=mid && j<=e){
if(a[i] < a[j]){
temp[k++] = a[i++];
}
else{
temp[k++] = a[j++];
}
}
while(i<=mid){
temp[k++] = a[i++];
}
while(j<=e){
temp[k++] = a[j++];
}
//We need to copy all element to original arrays
for(int i=s;i<=e;i++){
a[i] = temp[i];
}
}
void mergeSort(int a[],int s,int e){
//Base case - 1 or 0 elements
if(s>=e){
return;
}
//Follow 3 steps
//1. Divide
int mid = (s+e)/2;
//Recursively the arrays - s,mid and mid+1,e
mergeSort(a,s,mid);
mergeSort(a,mid+1,e);
//Merge the two parts
merge(a,s,e);
}
int main(){
int a[100];
int n;
printf("Enter No of elements you want in th array:");
scanf("%d",&n);
for(int i=0;i<n;i++){
printf("Enter No. %d :",i+1);
scanf("%d",&a[i]);
}
mergeSort(a,0,n-1);
for(int i=0;i<n;i++){
printf("%d\n",a[i]);
}
}