-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Sort.cpp
More file actions
72 lines (58 loc) · 1.42 KB
/
Merge_Sort.cpp
File metadata and controls
72 lines (58 loc) · 1.42 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
// Finding the number of connected components in an undirected graph
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &arr, int from, int to, int middle)
{
vector<int> newArray;
int currentFrom = from;
int currentTo = middle + 1;
while (currentFrom <= middle && currentTo <= to)
{
if (arr.at(currentTo) < arr.at(currentFrom))
{
newArray.push_back(arr.at(currentTo));
currentTo++;
}
else
{
newArray.push_back(arr.at(currentFrom));
currentFrom++;
}
}
while (currentFrom <= middle)
{
newArray.push_back(arr.at(currentFrom));
currentFrom++;
}
while (currentTo <= to)
{
newArray.push_back(arr.at(currentTo));
currentTo++;
}
int index = from;
for (int i = 0; i < newArray.size(); i++)
{
arr.at(index) = newArray.at(i);
index++;
}
}
void merge_sort(vector<int> &arr, int from, int to)
{
if (from < to)
{
int middle = (from + to) / 2;
merge_sort(arr, from, middle);
merge_sort(arr, middle + 1, to);
merge(arr, from, to, middle);
}
}
int main()
{
vector<int> testingArray = {6, 3, 5, 2, 1, 4};
merge_sort(testingArray, 0, testingArray.size() - 1);
for (int i = 0; i < testingArray.size(); i++)
{
cout << testingArray.at(i) << " ";
}
}