MergeSort Help

Okay so I literally cannot figure this out. It probably has to do with how I'm passing my pointers, but I can't figure why this my MergeSort method is not working. Any help would be incredible.

The basic problem is the code never stops running. I have a print method to print out the unsorted, partially sorted, and finally sorted array. But it becomes pretty clear by running the code that I'm accessing some random part of memory my output is just a bunch of random numbers (these are probably coming from when I call the print method while sorting).

But yea if anyone can help me figure this one out, I would really appreciate it.


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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99

#include <iostream>
using namespace::std;

void print(int* r, int length)
{
    for(int i=0; i<length; i++)
    {
        cout << r[i] << endl;
    }
}



int* merge(int* a, int* b, int alen, int blen)
{
    
    int i=0;
    int j=0;
    int dev[alen+blen+1];
    int* ans= dev;
    int k=0;
    print(a,alen);
    
    
    while((i<alen)&&(j<blen))
    {
        if(a[i]<=b[j])
        {
            ans[k]=a[i];
            i++;
            k++;
        }
        else
        {
            ans[k]=b[j];
            j++;
            k++;
        }
    }
    
    if(i>=alen)
    {
        while(k<(alen+blen))
        {
            ans[k]=b[j];
            j++;
        }
        
    }
    else if(j>=blen)
    {
        while(k<(alen+blen))
        {
            cout << ans[k]<< endl;
            ans[k]=a[i];
            i++;
        }
        
    }
        
    return ans;
}

int* mergesort(int* a, int len)
{
    if(len!=1)
    {
        int firsthalf=(len/2);
        int secondhalf= (len-firsthalf);
        
        int* b=mergesort(a,firsthalf);
        int* c=mergesort(a+firsthalf,secondhalf);
        
        int* ans= merge(b,c,firsthalf,secondhalf);
        return ans;
    }
    else{
        return a;
    }
    
    
}

int main()
{
    int b[10]={10,9,8,7,6,5,4,3,2,1};
    print(b,10);
    int* c=mergesort(b, 10);
    
    for(int i=0; i<10; i++)
    {
        cout << "" << endl;
    }
    
    print(c,10);
    return 0;
}
Last edited on
Invalid syntax on line 3. Nevermind, heh, it just looks wrong, but it's fine.

Also, at least explain what the problem is rather than just stating "there's a problem" ;)
Last edited on
Oh yes, that's probably important. I just updated my original post.
Last edited on
Topic archived. No new replies allowed.