C++ STL :Recursive Merge Sort (Sorting)

#include<iostream>
#include<vector>
#include<algorithm>

template<typename T>


void merge(std::vector<T>& left_vector,std::vector<T>& right_vector,std::vector<T>& merged_vector){

auto left=left_vector.begin();
auto right=right_vector.begin();
auto merged=merged_vector.begin();
auto left_end=left_vector.end();
auto right_end=right_vector.end();

while(left!=left_end&&right!=right_end){
if(*right<*left){
*merged=*right;
++right;
}
else{
*merged=*left;
++left;
}
++merged;
}
std::copy(left,left_end,merged);
std::copy(right,right_end,merged);
}

template<typename T>

void merge_sort(std::vector<T>& A){

if(A.size()<=1) return;

size_t mid=A.size()/2;
std::vector<T> left(A.begin(),A.begin()+mid);
std::vector<T> right(A.begin()+mid,A.end());
merge_sort(left);
merge_sort(right);
merge(left,right,A);
}

int main(){

std::vector<int> v={4,2,8,57,1,8,34,6};
merge_sort(v);
for(int i=0;i<v.size();i++){
std::cout<<v[i]<<" ";
}
}

Detailed Question and Solution

You may also like:
C++ STL : An example of Transform Algorithm
C++: Check if the String is Palindrome
Cool Websites you don't know about...
What programming languages do what?
How do I learn data structures and algorithms from scratch?

Popular Posts

Top 10 Web Sites Every Programmer Should Visit Daily

How do I improve my logical thinking and problem solving skills?

C++: STL Iterators