Your first mergesort()
call results in an infinite loop. beg < end
will always evaluate to true
as the value is not modified. Recursively calling mergesort()
creates copies of those integers. Any changes inside those functions have no effect on them. Consider removing the loop. Add a check such that the function does nothing if there's only one element to be sorted.
Now, assuming your mergesort()
is fixed, let's see the merge()
function. An element in your array might be ignored. For example, with beg
at 0, mid
at 2 and end
at 5. Your loop condition implies that you want i
to be from 0 to 1 and j
to be from 2 to 4. The fifth element is ignored. I believe you want i
to range from 0 to 2 and j
to range from 3 to 5, though. All while
must be fixed. (<=
instead?)
Furthermore, even if conditions are fixed, please check your j
value carefully. For example, if you have beg
at 0, end
at 1 and (an array with two elements), mid
atis obviously 0. Your 0merge()
, your will start with i
at 0 and j
will beat 0. First time the same and your loops are proneloop executes, if
condition is always false because they refer to copying same value twice, so else
executes and turns j
into 1. Another time the loop executes, if if
part executes then it's fine. But.
If else
part executes, i
is at 0, j
turns into 2. The loop exits. Next condition checking will result in else
being executed as i
is equal to mid
. As that part executes, the loop will run once, setting the third element of your array. It shouldn't do that at all. You're sorting two, not three. This may cause a segmentation fault if it goes over array's boundary. How about setting j
at mid + 1
instead?
You incorrectly specify conditions for for
loop. Comma simply ignores the first condition and only second is significant. Link the conditions with &&
operator instead. Better off, you only need one variable here. Just i
is enough. Make sure the value doesn't just start at 0. You don't want to accidentally replace the original array with garbage values trying to merge on the right side.
The condition for display()
should be i < 6
also, not i < 5
. Otherwise, the last element won't be displayed. And, lastly, don't forget to make it such that it doesn't fix to six elements. You might encounter some problems trying with bigger element count.
Good luck with your code!