-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.cpp
99 lines (83 loc) · 1.86 KB
/
merge_sort.cpp
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
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &arr, int low, int mid, int high)
{
vector<int> temp;
int left = low;
int right = mid + 1;
while (left <= mid && right <= high)
{
if (arr[left] < arr[right])
{
temp.push_back(arr[left]);
left++;
}
else
{
temp.push_back(arr[right]);
right++;
}
}
while (left <= mid)
{
temp.push_back(arr[left]);
left++;
}
while (right <= high)
{
temp.push_back(arr[right]);
right++;
}
for (int i = low; i <= high; i++)
{
arr[i] = temp[i - low];
}
};
// reverse a array function LeetCode-Q 493
void countNoOfPair(vector<int> &arr, int low, int mid, int high, int& count)
{
int right = mid + 1;
cout << arr.size() << " " << low << " " << mid << " " << high << endl;
for(int i =0; i<arr.size(); i++){
cout << arr[i] << " ";
}
cout << endl;
for (int i = low; i <= mid; i++)
{
while (right <= high && (long long)arr[i] > 2 * (long long)arr[right]){
right++;
}
count += (right - (mid + 1));
}
}
void mergeAndDivide(vector<int> &arr, int low, int high, int& count)
{
if (low == high)
return;
int mid = (low + high) / 2;
mergeAndDivide(arr, low, mid, count);
mergeAndDivide(arr, mid + 1, high, count);
// countNoOfPair(arr, low, mid, high, count);
merge(arr, low, mid, high);
};
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int count = 0;
mergeAndDivide(arr, 0, n - 1, count);
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
// leetCode - Q 493
// cout << count;
return 0;
}