#include<iostream>
#include<vector>
using namespace std;
// the interval from [s to m] and [m+1 to e] in v are sorted
// the function will merge both of these intervals
// such the interval from [s to e] in v becomes sorted
void MergeSortedIntervals(vector<int>& v, int s, int m, int e) {
// temp is used to temporary store the vector obtained by merging
// elements from [s to m] and [m+1 to e] in v
vector<int> temp;
int i, j;
i = s;
j = m + 1;
while (i <= m && j <= e) {
if (v[i] <= v[j]) {
temp.push_back(v[i]);
++i;
}
else {
temp.push_back(v[j]);
++j;
}
}
while (i <= m) {
temp.push_back(v[i]);
++i;
}
while (j <= e) {
temp.push_back(v[j]);
++j;
}
for (int i = s; i <= e; ++i)
v[i] = temp[i - s];
}
// the MergeSort function
// Sorts the array in the range [s to e] in v using
// merge sort algorithm
void MergeSort(vector<int>& v, int s, int e) {
if (s < e) {
int m = (s + e) / 2;
MergeSort(v, s, m);
MergeSort(v, m + 1, e);
MergeSortedIntervals(v, s, m, e);
}
}
int main() {
int n;
vector<int> v;
cout << "Enter Size of Vector : ";
cin >> n;
v = vector<int>(n);
cout << "Enter Elements of Vector : ";
for (int i = 0; i < n; ++i) {
cin >> v[i];
}
MergeSort(v, 0, n - 1);
cout << "
Vector Obtained After Sorting: ";
for (int i = 0; i < n; ++i) {
cout << v[i] << ' ';
}
}
Code Example |
---|
Cpp :: c++ iterate map |
Cpp :: rand c++ |
Cpp :: sleep system function linux c++ |
Cpp :: two pointer in c++ |
Cpp :: print all elements of vector c++ |
Cpp :: height of bst cpp |
Cpp :: c++ simple car game |
Cpp :: string stream in c++ |
Cpp :: c++ function for checking if a sting is a number |
Cpp :: cpp float to string |
Cpp :: less than operator overloading in c++ |
Cpp :: C++ press enter to continue function |
Cpp :: minimum value in array using c++ |
Cpp :: matrix transpose in c++ |
Cpp :: int to hex arduino |
Cpp :: comparator for priority queue c++ |
Cpp :: declaring 2d dynamic array c++ |
Cpp :: c++ vector declaration |
Cpp :: cpp vector2 |
Cpp :: how to code string to int converter c++ |
Cpp :: even and odd sum in c++ |
Cpp :: find second highest number in c++ |
Cpp :: c++ pass array to a function |
Cpp :: cin getline |
Cpp :: arduino xor checksum |
Cpp :: 2d vector in cpp |
Cpp :: how to initialize vector |
Cpp :: c++ replace |
Cpp :: demonstrate constructor |
Cpp :: cpp define |