C++ STL: Merge_Sort using Vector (Sorting)

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
void merge_(vector<int>& v,int p,int q,int r){
int n1=q-p+1;  int n2=r-q; // here n1 was written as q+p+1
vector<int>L(n1);
vector<int>R(n2);
for(int i=0;i<n1;i++){
    L[i]=v[p+i];
}
for(int j=0;j<n2;j++){
    R[j]=v[q+j+1];
}
int i=0,j=0;
int k; // declaring k outside
for( k=p;k<=r && i<n1 && j < n2;k++){ // if i >= n1 || j> = n2 then it will access random memory
    if(L[i]<=R[j]){
        v[k]=L[i];
        i++;
    }
    else{
        v[k]=R[j];
        j++;
    }
}
for(i = i;i<n1;++i) // these are the two loops must be there if L or R runs out
{
    v[k] = L[i];
    k++;
}


for(j = j;j<n2;j++)

    {
        v[k] = R[j];
        k++;
    }
}

void merge_sort(vector<int>& v,int p,int r){

if(p<r){
    int q=(p+r)/2;
    merge_sort(v,p,q);
    merge_sort(v,q+1,r);
    merge_(v,p,q,r);
}
}

int main()

{
vector<int>vec;
vec.push_back(13);
vec.push_back(5);
vec.push_back(7);
vec.push_back(7);
vec.push_back(4);
vec.push_back(2);
vec.push_back(10);
for(int n=0;n<7;n++){
    cout<<vec[n]<<" ";
}
cout<<"\n";
int sz=vec.size();
merge_sort(vec,0,6);
for(int n=0;n<sz;n++){
    cout<<vec[n]<<" ";
}
    return 0;
}

You may also like:
C++:Recursive Merge Sort
C++: Insertion Sort
C++: Reading Elements from Vector until EOL
C++:Working With Files -1
What programming languages do what?

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