i'm writing insertion sort method , i've run trouble -
private int getinsertionposition(int currpos){ int val = this.tosort.get(currpos); int index = currpos; for(int = 0; < currpos; i++){ if(val < this.tosort.get(i)){ index = i; } } return index; } private void move(int from, int to){ int num = tosort.get(from); tosort.remove(from); tosort.add(to, num); system.out.println("moved " + + " " + to); } public void performsort(){ for(int = 1; < original.length; i++){ move(i,getinsertionposition(i)); system.out.println(this.tosort.tostring()); } }
i have couple debug lines in there, printing out index it's moving elements of arraylist / to.
however, weird operations it's moving seemingly arbitrary values wrong index, i.e.
" [7, 18, 29, 3, 2, 4, 24, 18, 18, 13] moved 3 2 [7, 18, 3, 29, 2, 4, 24, 18, 18, 13] "
any help? i'm 99% sure issue getinsertionposition method.
yes problem in getinsertionpoint
. need return first index has value greater value. @ moment returning last index greater value.
try:
private int getinsertionposition(int currpos) { (int = 0; < currpos; i++) { if (tosort.get(currpos) < this.tosort.get(i)) { return i; } } return currpos; }
alternatively, if familiar java 8 streams:
return intstream.range(0, currpos) .filter(i -> tosort.get(currpos) < tosort.get(i)) .findfirst().orelse(currpos);
Comments
Post a Comment