i trying use selection sort algorithm in version of doubly linked list wrote myself. question can assume there no errors elsewhere other code post (at least, none relevant question). have done plenty of testing.
here method:
public void selectionsort(){ listitem front = head; listitem current; t currentlowest; t potentiallowest; int lowestindex = 0; (int = 0; a<count-1; a++){ system.out.println("a: "+a); currentlowest = (t) front.content; front = front.next; current = front.next; for(int = a+1; i<count; i++){ system.out.println("i: "+i); **(29)** potentiallowest = (t) current.content; if (potentiallowest.compareto(currentlowest)==-1) { currentlowest = (t) current.content; lowestindex = i; } if(current.next == null)break; current = current.next; } system.out.println("swapped"+a+","+lowestindex); swap(a, lowestindex); }
}
it sorting list of 100 integers. here last bit of output before receive null pointer on line 29 (marked).
swapped95,97
a: 96 i: 97 i: 98
swapped96,97
a: 97 i: 98
swapped97,97
a: 98 i: 99 (null pointer)
i had working earlier horribly optimized. after making changes, i'm stuck this. ideas?
thanks time.
i think problem might arise in first iteration of sorting loop. considering first line in function (listitem front = head
) points front
first element of list, seems calling: front = front.next; current = front.next;
you 'skip' element @ index 1 in list , start comparison loop of element @ index 2.
for example, if (unsorted) list looks this:
[54, 11, 25, 34]
it like
[25, 11, 54, 34]
after first iteration of sorting algorithm. since next iteration start @ index 1, element 11 never placed @ index 0 though lowest element in list.
it might inaccuracy causes null pointer problem @ end of list. consider putting statement front = front.next;
after inner loop , before swap(a, lowestindex);
statement. prevent possible error in first iteration , might solve problem.
Comments
Post a Comment