Merge Sort problem

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
void merge_sort(int *A, int p, int r)
{
    if(p<r)
    {
        int q;
        q=(p+r)/2;
        cout<<"q: "<<q<<endl;
        merge_sort(A, p, q);
        merge_sort(A, q+1, r);
        merge(A, p, q, r);
        cout<<endl;
    }
}

void merge(int *A, int p, int q, int r)
{
    int n1, n2, i, j, L[20], R[20];

    n1 = q-p+1;
    n2 = r-q;

    for(i=0; i<n1; i++)
    {
        L[i]=A[p+i];
    }
    //L[n1]=1000000;
    for(j=0; j<n2; j++)
    {
        R[j]=A[q+j+1];
    }
    //R[n2]=1000000;
    i=0;
    j=0;

    for(int k=p; k<=r; k++)
    {
        if((i<n1 && j<n2) && L[i]<=R[j] )
        {
            A[k]=L[i];
            cout<<"a"<<A[k]<<" ";
            i++;
        }
        else if((i<n1 && j<n2) && L[i]>R[j])
        {
            A[k]=R[j];
            cout<<"b"<<A[k]<<" ";
            j++;
        }
        else if(i==n1)
        {
            A[k]=R[j];
        }
        else if(j==n2)
        {
            A[k]=L[i];
        }
    }
}

My code doesn't work for inputs not a power of 2. Any idea how I might make this work for any kind of input?
Last edited on
Topic archived. No new replies allowed.