Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Wierd Insertion sort problem

What I'm trying to do is sort a certain number of objects that are read from a text file, say for example a list of names. It uses different sorting algorithims, like the one below to accomplish this, while also keeping track of the number of compares/swaps. This should be pretty straight forward, all the other ones I have work perfectly fine but for some reason this one is giving screwy results.

For example, say I have a unsorted list of names, while the sorted list should
look like this:

AMBER
AMY
BART
BILL
BOB
CURT
DAN
DAVE
JOHNNY
MARK
MIKE
TOMMY

It comes out something like this

AMBER
AMBER
AMBER
AMBER
AMBER
AMBER
AMBER
AMBER
AMBER
MIKE
AMY
AMY
AMY
AMY
AMY
:confused:

I usually don't have any problems with stuff like this, but for the life of me can't figure out what the heck is wrong with this. Here's the code below. I'll keep trying to figure it out, but if anybody can see something that I'm not seeing with this code, that would be awesome. Thanks a lot. The compares++, and swaps++ are there just to keep track of them.

public static void insertionSort (List data)
{

Comparable tmp;
int i, j;

for(i = 1; i < data.size(); i++)
{

tmp = (Comparable)data.get(i);

for(j = i; (j > 0) && (tmp.compareTo(data.get(j - 1)) < 0)
; j--){
compares++;
data.set(j, data.get(j - 1)) ;
data.set(j, tmp) ;
swaps++;
}
}

}
[1722 byte] By [Jinjoe] at [2007-11-11 10:23:10]