-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.cpp
More file actions
73 lines (43 loc) · 1.03 KB
/
MergeSort.cpp
File metadata and controls
73 lines (43 loc) · 1.03 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
#include "bits/stdc++.h"
using namespace std;
//function to merge two array
vector<int> merging(vector<int> a,vector<int> b){
int x = (int)a.size() + (int)b.size();
vector<int> v(x);
size_t p = 0;
size_t q = 0;
size_t i = 0;
while(p < a.size() && q < b.size()) {
if(a[p] < b[q]){
v[i++] = a[p++];
}else{
v[i++] = b[q++];
}
}
while(p < a.size()) {
v[i++] = a[p++];
}
while(q < b.size()) {
v[i++] = b[q++];
}
return v;
}
//splitting the array and then merging the array
vector<int> mergeSort(vector<int> k){
int x = (int)k.size();
if(x<2){
return k;
}
vector<int> a(k.begin(),k.begin()+(x/2));
vector<int> b(k.begin()+(x/2),k.end());
return merging(mergeSort(a),mergeSort(b));
}
int main(){
vector<int> v = {3,5,34,11,32,7,35,54,67,89,23,4,3};
//calling the merge function
vector<int> b = mergeSort(v);
for(int i=0;i<(int)b.size();++i){
cout << b[i] << "\n";
}
return 0;
}