-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.cpp
More file actions
85 lines (73 loc) · 1.93 KB
/
Copy pathmergesort.cpp
File metadata and controls
85 lines (73 loc) · 1.93 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
74
75
76
77
78
79
80
81
82
83
84
85
/* TODO: Try to write merge sort! Prototypes are given below using vectors,
* but if you would prefer, arrays are fine too. */
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <vector>
using std::vector;
/* This should take two SORTED vectors, L and R, and return another vector
* which is sorted and contains all values from L and R. */
vector<int> merge(const vector<int>& L, const vector<int>& R){
vector<int> result;
size_t i = 0, j = 0;
// Merge two vectors and compare their elements
while (i < L.size() && j < R.size()) {
if (L[i] < R[j]) {
result.push_back(L[i]);
i++;
} else {
result.push_back(R[j]);
j++;
}
}
// Add remaining elements from L, if any
while (i < L.size()) {
result.push_back(L[i]);
i++;
}
// Add remaining elements from R, if any
while (j < R.size()) {
result.push_back(R[j]);
j++;
}
return result;
}
void mergeSort(vector<int>& V){
if (V.size() <= 1) {
return; // Base case: a vector of size 0 or 1 is already sorted
}
// Divide the vector into two halves
size_t mid = V.size() / 2;
vector<int> left(V.begin(), V.begin() + mid); // Left half of the vector
vector<int> right(V.begin() + mid, V.end()); // Right half of the vector
// Recursively sort the two halves
mergeSort(left);
mergeSort(right);
// Merge the sorted halves back into the original vector V
V = merge(left, right);
}
int main()
{
vector<int> nums;
int x;
// Input numbers from the user
cout << "Enter numbers to be sorted (end with non-numeric input):\n";
while (cin >> x) {
nums.push_back(x);
}
// Call mergeSort to sort the numbers
mergeSort(nums);
// Output the sorted vector
cout << "Sorted numbers: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
// vim:foldlevel=2
/*Merge Sort is a divide-and-conquer algorithm:
*Divide the array into two halves.
*Recursively sort both halves.
*Merge the two sorted halves into a single sorted array.*/