-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.cpp
82 lines (67 loc) · 1.76 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
#include <iostream>
#include <vector>
// Merge two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(std::vector<int>& arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
// Create temporary arrays
std::vector<int> left(n1);
std::vector<int> right(n2);
// Copy data to temporary arrays left[] and right[]
for (int i = 0; i < n1; i++) {
left[i] = arr[l + i];
}
for (int j = 0; j < n2; j++) {
right[j] = arr[m + 1 + j];
}
// Merge the temporary arrays back into arr[l..r]
int i = 0;
int j = 0;
int k = l;
while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}
// Copy the remaining elements of left[], if any
while (i < n1) {
arr[k] = left[i];
i++;
k++;
}
// Copy the remaining elements of right[], if any
while (j < n2) {
arr[k] = right[j];
j++;
k++;
}
}
// Main function to perform merge sort
void mergeSort(std::vector<int>& arr, int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
int main() {
std::vector<int> numbers = {38, 27, 43, 3, 9, 82, 10};
int n = numbers.size();
mergeSort(numbers, 0, n - 1);
std::cout << "Sorted array: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}