I'm implementing a merge sort algorithm in my code in order to sort data which is currently held in an arraylist of arraylists. The splits seem to be functioning fine (i've been doing a lot of System.out.print at every stage to make sure its doing what I think it's doing) However, when I get into the merge code I don't seem to be able to get it to run. I get stuck in an infinite loop and when I print what's going on to the console I get 0 over and over again from the output at line No. 15 in Merge.java
Can anyone see any rookie errors? I've tried playing with how the loops are nested in case I missed a curly bracket in the right place.
So below are my two simple classes to implement the merge sort
Michael Comerford wrote:Can anyone see any rookie errors? I've tried playing with how the loops are nested in case I missed a curly bracket in the right place.
That's a rookie error right there. It tells me you don't really know how your code works so you're trying random changes hoping for a miracle. What you've shared is prodigiously complex and terribly difficult to read. Give your variables real names! It would help to break your problem into small pieces. You've done that to some extent with your Merge class, but you don't need more than one class for this. Really the addition of a helper class here is just unnecessary added complexity. And like your MergeSort class, your helper class is just one huge method. I recommend you start over, from scratch.
How would you perform this task without a computer?
Write down that process as a series of instructions. Go through the process a few times with test data. Write everything out with pencil and paper, in plain language, before writing a single Java command. Start with a broad outline, then take what you've written and rewrite it, filling in the details. Repeat this process, always breaking things down into smaller tasks. Tasks that get performed over and over are prime candidates for methods. When you reach the point when you can't break things down any more, then you will be ready to write Java code.
posted 7 years ago
Thanks Dennis, you're totally right. Once I sat down and actually went through the process I was attempting to automate step by step and wrote out dummy datasets etc. it made much more sense and I have now redesigned my code and it is now working for my purposes.