java - What's wrong with my insertion sort? -
i'm trying sort large datafile using insertion-based sorting algorithm, code runs fine output incorrect. i've studied on , on absolutely no avail, can see i've gone wrong?
public void sort(comparable[] items) { (int = 1; < items.length; i++) { comparable temp = items[i]; int j = - 1; while (j >= 0 && items[j].compareto(items[j]) > 0) { items[j + 1] = items[j]; j = j - 1; } items[j] = temp; } }
an example datafile have produced is...
2 1 3 5 9 6 7 4 8
and output should 1,2,3,4... - instead 1 3 5 9 6 7 4 8 8
items[j].compareto(items[j])
should items[j].compareto(temp)
, otherwise you're comparing item against - need comparing against object want insert.
then items[j] = temp;
cause arrayindexoutofboundsexception
because, @ end of loop, items[j]
smaller temp
, or j == -1
, need insert @ position after - simplest fix changing items[j+1] = temp;
.
Comments
Post a Comment