Merge sort

Oct 8, 2012 at 9:39pm
This is the code I've done for the merge function of my merge sort algorithm.
When called the function successfully merges the two arrays passed in however it does not sort them. I can not figure out why this happens. If I output the result array it is just the right array and then the left array. I thought the comparisons made in the for loop should have put them in order from smallest to largest. Any help is appreciate thanks.
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
int *merge(int *left, int *right, int numl, int numr)
{
        int *result = new int[numl*2];
        int i = 0;
        int j = 0;
        int k = 0;
        while(numl > 0 || numr > 0)
        {
	        if(numl > 0 && numr > 0)
	        {
		        if(left[i] <= right[j])
		        {
			        result[k] = left[i];
		                k++;
			        i++;
		                numl--;
		        }
		        else
		        {
			        result[k] = right[j];
			        k++;
			        j++;
			        numr--;
	                }
	        }
	        else if(numl > 0)
	        {
		        result[k] = left[i];
		        k++;
 		        i++;
	                numl--;
	        }
	        else if(numr > 0)
	        {
		         result[k] = right[j];
		         k++;
		         j++;
		         numr--;
	        }
        }
        return result;
}
Last edited on Oct 8, 2012 at 11:32pm
Oct 8, 2012 at 10:12pm
Use code tags

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
int *merge(int *left, int *right, int numl, int numr)
{
int *result = new int[numl*2];
int i = 0;
int j = 0;
int k = 0;
while(numl > 0 || numr > 0)
{
if(numl > 0 && numr > 0)
{
if(left[i] <= right[j])
{
result[k] = left[i];
k++;
i++;
numl--;
}
else
{
result[k] = right[j];
k++;
j++;
numr--;
}
}
else if(numl > 0)
{
result[k] = left[i];
k++;
i++;
numl--;
}
else if(numr > 0)
{
result[k] = right[j];
k++;
j++;
numr--;
}
}
return result;
}
Oct 9, 2012 at 12:11am
The code is (more or less) correct if you're feeding it two already sorted arrays. I say more or less because the code will fail if numr > numl. It may be that is always true. Obviously we can't know from this snippet of code.

Changing the size allocated by new to new int[numl+numr] would be less fragile.

This function won't do anything useful, though, if fed arrays that are not already sorted.
Oct 9, 2012 at 12:37am
Yeah, the problem is that it is supposed to sort it as well, not just combine it. I though that in my if statements comparing left and right values and putting them into the solution I was sorting them but this is clearly not the case.
Topic archived. No new replies allowed.