Bubble Sort logical error VB.NET -
this program suppose sort records(in arysort) in ascending order last name(index 1 in arytemp , arytemp2) , place result in list box on old, preloaded, unsorted records.
it sorts them strangely, have click multiple times ascending button actual sort result suppose clicking button once.
why doesn't sort items single mouse click?
the source:
public class form1 dim file_name string = "students.txt" dim numberofrecords integer 'total number of records private sub form1_load(byval sender system.object, byval e system.eventargs) handles mybase.load if system.io.file.exists(file_name) = true dim objreader new system.io.streamreader(file_name) while objreader.peek() <> -1 lstbox.items.add(objreader.readline) numberofrecords += 1 loop objreader.close() end if end sub private sub btnascending_click(byval sender system.object, byval e system.eventargs) handles btnascending.click 'load students array dim arysort(numberofrecords - 1) string dim arytemp() string 'holds first record's last name dim arytemp2() string 'holds second record's last name = 0 numberofrecords - 1 arysort(i) = lstbox.items(i) next dim temp string 'holds temporary record dim k integer = 0 arysort.length - 2 arytemp = split(arysort(i), " ") k = + 1 arysort.length - 1 arytemp2 = split(arysort(k), " ") if arytemp(1) < arytemp2(1) temp = arysort(k) arysort(k) = arysort(i) arysort(i) = temp end if next next lstbox.items.clear() numberofrecords = 0 = 0 arysort.length - 1 lstbox.items.add(arysort(i)) numberofrecords += 1 next end sub end class
if need sort list (as in comment), don't implement own sort mechanism use 1 of .net:
' define how want compare items ' function comparebylastname(byval item1 string, byval item2 string) integer return string.compare(item1.split(" ")(1), item2.split(" ")(1)) end function private sub btnascending_click(byval sender system.object, byval e system.eventargs) handles btnascending.click ' load students array ' dim arysort(numberofrecords - 1) string = 0 numberofrecords - 1 arysort(i) = lstbox.items(i) next ' use built-in .net magic ' array.sort(arysort, addressof comparebylastname) ' write values list box ' lstbox.items.clear() numberofrecords = 0 = 0 arysort.length - 1 lstbox.items.add(arysort(i)) numberofrecords += 1 next end sub
this uses built-in quicksort algorithm of .net class library. here's documentation of method using: array.sort(t(), comparison(of t)).
Comments
Post a Comment