• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with InsertionSort Algorithm  RSS feed

 
Unnsse Khan
Ranch Hand
Posts: 511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello again,

I've been revamping my Data Structures skills for a more modern JDK 1.5 (back in '96, when I was in college, I used GNU C in my Data Structures course).

Reached a particular problem...

Here's the TestCase:



Here's the "Object under Test":



Here's the error message that Eclipse's JUnit TestRunner gives me (its a failing test!):



What am I possibly doing wrong? Is there a better way to test and/or implement an InsertionSort than the method that I am using?

With thanks and happy programming!
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first index in a Java array is 0, and it the last is array.length - 1. In this loop:

The first element you try to access is a[1] (which is fine, assuming you have an array with more than one element, which is not always true), and the last element you try to access is a[a.length] which is *never* a valid index for a Java array.
[ February 21, 2008: Message edited by: Garrett Rowe ]
 
Unnsse Khan
Ranch Hand
Posts: 511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garrett,

You are correct! It was the i <= a.length that broke the test case!

It should be:



Now, the test case runs with no fail!

Many, many thanks!
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens when you add this test of a trivial case:

 
Unnsse Khan
Ranch Hand
Posts: 511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garrett,

I placed your test fixture inside my TestCase and ran it through the JUnit TestRunner in Eclipse and it still worked!



Are you implying there's something wrong with the implementation of the insertionSort() method?

Thank you for contributing and collaborating with me!

Happy programming.
[ February 22, 2008: Message edited by: Unnsse Khan ]
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was, but I didn't take into account that once you corrected the loop that the error I saw earlier would be fixed. Thats what tests are for though. Happy Coding!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!