-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge.cpp
More file actions
55 lines (41 loc) · 1.16 KB
/
Copy pathmerge.cpp
File metadata and controls
55 lines (41 loc) · 1.16 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
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void merge(vector<int>& arr, int l, int m, int r) {
vector<int> temp;
int i = l, j = m;
while (i < m && j < r) {
if (arr[i] <= arr[j])
temp.push_back(arr[i++]);
else
temp.push_back(arr[j++]);
}
while (i < m) temp.push_back(arr[i++]);
while (j < r) temp.push_back(arr[j++]);
for (int k = 0; k < temp.size(); k++)
arr[l + k] = temp[k];
}
void iterativeMergeSort(vector<int>& arr) {
int n = arr.size();
for (int currSize = 1; currSize < n; currSize *= 2) {
for (int leftStart = 0; leftStart < n - 1; leftStart += 2 * currSize) {
int mid = min(leftStart + currSize, n);
int rightEnd = min(leftStart + 2 * currSize, n);
merge(arr, leftStart, mid, rightEnd);
}
}
}
int main() {
srand(time(0));
vector<int> arr(100);
// Generate 100 random elements
for (int i = 0; i < 100; i++)
arr[i] = rand() % 100;
iterativeMergeSort(arr);
// Print sorted array
for (int x : arr)
cout << x << " ";
return 0;
}