I have an unusual problem. I’ve been implementing Merge Sort and have encountered the following: The method works correctly except on the last pass. Given a random Integer array as input returns an Integer array where the first half and the second half are sorted separately. The merge works correctly except on the last pass. After fiddling with the debugger for a few hours I figured out that “mention point” is always evaluating to false on the last pass, even though it shouldn’t based on the values.
All help is appreciated.
public static Integer[] mergeSort(Integer[] input)
{
if (input.length == 1) return input;
int splittle = input.length / 2;
Integer[] first = new Integer[splittle];
Integer[] second = new Integer[input.length - splittle];
for (int i = 0; i < splittle; i++)
first[i] = input[i];
for (int i = splittle; i < input.length; i++)
second[i - splittle] = input[i];
mergeSort(first);
mergeSort(second);
LinkedList<Integer> returner = new LinkedList<Integer>();
PriorityQueue<Integer> sFirst = new PriorityQueue<Integer>();
PriorityQueue<Integer> sSecond = new PriorityQueue<Integer>();
for (int i = 0; i < first.length; i++)
sFirst.offer(first[i]);
for (int i = 0; i < second.length; i++)
sSecond.offer(second[i]);
// while (!sFirst.isEmpty()&&!sSecond.isEmpty())
// returner.add((sFirst.peek()>=sSecond.peek() ?
// sFirst.poll():sSecond.poll()));
// expansion of line above for debugging purposes
while (!sFirst.isEmpty() && !sSecond.isEmpty())
{
int temp = 0;
if (sFirst.peek() >= sSecond.peek())
temp = sFirst.poll(); // Mention point
else
temp = sSecond.poll();
returner.add(temp);
}
while (!sFirst.isEmpty())
returner.add(sFirst.poll());
while (!sSecond.isEmpty())
returner.add(sSecond.poll());
return returner.toArray(new Integer[0]);
}
The problem is inside your
whilecode, and more specific when you use thepoll()method.You had:
when you should had:
Before, in an input like this:
you would have
if (-9 >= 4)which would be false, so you would do theelsepart, which wouldpoll()fromsSecondalthough you shouldpoll()fromsFirst.-9should be the first element to be added in thereturnerlist, not4.Also (based on ccoakley answer) change, you should use the returned array from
mergeSort(), which can be done easily by:You can have a look of the working code (after the changes) here.