need help with my merge sort code!

#include <iostream>
#include <algorithm>
using namespace std;
void merge_sort_array(int* v, int l, int r) {
if ((r-l)>1)
{
int mid=(r+l)/2;
merge_sort_array(v, l ,mid);
merge_sort_array(v, mid, r);
int L[mid-l];
for(int i=0;i<mid-l;i++){L[i]=v[l+i];}
int R[r-mid];
for(int i=0;i<r-mid;i++){R[i]=v[mid+i];}
int i=0;
int j=0;
int k=0;
while( i<mid-l && j<r-mid )
{
if(L[i]<R[j])
{v[k]=L[i];i++;}
else
{v[k]=R[j];j++;}
k++;
}
while(i<mid-l)
{v[k]=L[i];i++;k++;}
while(j<r-mid)
{v[k]=R[j];j++;k++;}
}
}


int main()
{

int b[]={5,2,1,3,4};
int n=end(b)-begin(b);
for ( int i=0;i<n;i++)
cout<<b[i]<<endl;
merge_sort_array(b,0,5);
for ( int i=0;i<n;i++)
cout<<b[i]<<endl;
}


The result does not turn out right.
Don't know where goes wrong
Sorry, not interested in deciphering that. [code] block please?
closed account (48T7M4Gy)
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
#include <iostream>
#include <algorithm>
using namespace std;
void merge_sort_array(int* v, int l, int r) {
    if ((r-l)>1)
    {
        int mid=(r+l)/2;
        merge_sort_array(v, l ,mid);
        merge_sort_array(v, mid, r);
        int L[mid-l];
        for(int i=0;i<mid-l;i++){L[i]=v[l+i];}
        int R[r-mid];
        for(int i=0;i<r-mid;i++){R[i]=v[mid+i];}
        int i=0;
        int j=0;
        int k=0;
        while( i<mid-l && j<r-mid )
        {
            if(L[i]<R[j])
            {v[k]=L[i];i++;}
            else
            {v[k]=R[j];j++;}
            k++;
        }
        while(i<mid-l)
        {v[k]=L[i];i++;k++;}
        while(j<r-mid)
        {v[k]=R[j];j++;k++;}
    }
}


int main()
{
    
    int b[]={5,2,1,3,4};
    int n=end(b)-begin(b);
    for ( int i=0;i<n;i++)
        cout<<b[i]<<endl;
    merge_sort_array(b,0,5);
    for ( int i=0;i<n;i++)
        cout<<b[i]<<endl;
}
closed account (48T7M4Gy)
Please use code tags. <> in the toolbox on the right.

As a tip, for clarity and self-documenting code, single letter variable names are not good, whitespace is good, and writing lines like line 13 almost guarantees nobody will read let alone understand it - it's not good programming.

The machine couldn't care less about line spacing. Regrettably you are dealing with human readers who expect the equivalent of paragraph spacing :)

for(int i=0;i<r-mid;i++){R[i]=v[mid+i];} is cutesy junk TBH

1
2
3
4
for(int i = 0; i < r-mid; i++ )
{
    R[i] = v[mid+i];
}
// IS READABLE BY A HUMAN (WHETHER IT's RIGHT OR NOT

http://www.geeksforgeeks.org/merge-sort/
Registered users can post here. Sign in or register to post.