forked from MukulCode/CodingClubIndia
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
76 lines (68 loc) · 1.41 KB
/
MergeSort.cpp
File metadata and controls
76 lines (68 loc) · 1.41 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
#include <bits/stdc++.h>
using namespace std;
void Printarray(vector<int> array)
{
for (int i = 0; i < array.size(); i++)
{
cout << array[i] << " ";
}
cout << endl;
}
void merge_array(vector<int> &a,int start,int mid,int stop)
{
int i = start, j = mid+1, k = start;
vector<int> result(a.size());
while (i <= mid && j <=stop )
{
if (a[i] < a[j])
{
result[k] = a[i];
i++;
}
else
{
result[k] = a[j];
j++;
}
k++;
}
while (i <= mid)
{
result[k] = a[i];
i++;
k++;
}
while (j <= stop)
{
result[k] = a[j];
j++;
k++;
}
for (int i = start; i <=stop; i++)
{
a[i]=result[i];
}
Printarray(a);
}
void merge_sort(vector<int> &array,int start,int stop)
{
if(start>=stop)return;
int mid=start+(stop-start)/2;
merge_sort(array,start,mid);
merge_sort(array,mid+1,stop);
merge_array(array,start,mid,stop);
}
int main()
{
int n;
cout<<"Enter the Number of Elements in Input Array : ";
cin>>n;
cout<<"Enter space-separated Elements of Input Array : ";
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin>>a[i];
}
Printarray(a);
merge_sort(a,0,a.size()-1);
}