me
by Mac1ek from LinuxQuestions.org on (#6Q2RC)
Hello All. It is my implementation of merge sort algorithm in c++. I need opinion it is correct example:
Code:#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
template<typename T> std::vector<T>& merge(std::vector<T>& vec, typename std::vector<T>::size_type p, typename std::vector<T>::size_type q, typename std::vector<T>::size_type r) {
std::vector<T> L(vec.begin()+p, vec.begin()+q);
std::vector<T> R(vec.begin()+q, vec.begin()+r);
typename std::vector<T>::size_type i = 0, j = 0, k = p;
while(i < L.size() && j < R.size()) {
if(L[i] < R[j]) {
vec[k] = L[i];
++i;
}
else {
vec[k] = R[j];
++j;
}
++k;
}
while(R.begin()+j!=R.end()) {
L.push_back(R[j]);
++j;
}
while(L.begin()+i!=L.end()) {
vec[k] = L[i];
++k;
++i;
}
return vec;
}
template <typename T> std::vector<T>& merge_sort(std::vector<T>& vec, typename std::vector<T>::size_type p, typename std::vector<int>::size_type r) {
if((r-p) < 2) {
return vec;
}
auto q = ((p+r)/2);
merge_sort(vec, p, q);
merge_sort(vec, q, r);
return merge(vec, p, q, r);
}You can use them in main:
Code:auto main() -> int {
std::vector<int> vec({23432, 3454, 3, 33, 22, 1, 75});
std::vector<int> result = merge_sort(vec, 0, 7);
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, " "));
return (0);
}Any comment welcome.
Thanks for answer.
Code:#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
template<typename T> std::vector<T>& merge(std::vector<T>& vec, typename std::vector<T>::size_type p, typename std::vector<T>::size_type q, typename std::vector<T>::size_type r) {
std::vector<T> L(vec.begin()+p, vec.begin()+q);
std::vector<T> R(vec.begin()+q, vec.begin()+r);
typename std::vector<T>::size_type i = 0, j = 0, k = p;
while(i < L.size() && j < R.size()) {
if(L[i] < R[j]) {
vec[k] = L[i];
++i;
}
else {
vec[k] = R[j];
++j;
}
++k;
}
while(R.begin()+j!=R.end()) {
L.push_back(R[j]);
++j;
}
while(L.begin()+i!=L.end()) {
vec[k] = L[i];
++k;
++i;
}
return vec;
}
template <typename T> std::vector<T>& merge_sort(std::vector<T>& vec, typename std::vector<T>::size_type p, typename std::vector<int>::size_type r) {
if((r-p) < 2) {
return vec;
}
auto q = ((p+r)/2);
merge_sort(vec, p, q);
merge_sort(vec, q, r);
return merge(vec, p, q, r);
}You can use them in main:
Code:auto main() -> int {
std::vector<int> vec({23432, 3454, 3, 33, 22, 1, 75});
std::vector<int> result = merge_sort(vec, 0, 7);
std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, " "));
return (0);
}Any comment welcome.
Thanks for answer.