I just wrote a quick tutorial/code snippet on how to bubble sort a list of numbers in an array (this method can also be applied to sorting strings).
First off, why would you need to sort stuff?
There are numerous times that you might want to sort a list. Maybe you are making an RPG, and you wan't the player's inventory to be listed alphabeticly. Maybe you're doing a multiplayer game, and you want to list servers by # of players or ping.... ect. ect.
The bubble sort algorithm works like this:
start at the top of the array, and run through the array using a for loop. Compare each element of the array with the element below it. If the first element is greater than the second, swap 'em. It keeps going until the end of the array, then it runs through the algorithm again, until no swaps occur. The only big problem with bubble sorting is that it is a O(n2), which means the time it takes to calculate grows exponentially the more elements you try to sort.
Maybe if I feel brave over the weekend, I'll attempt a QuickSort example
(n log n by the way, which grows much slower than the exponential methods)
Code:
`bubble sort example
`by esc
sync on:sync rate 0:hide mouse:randomize timer()
`number of elements
length=25
`create the numerical array you wish to sort
dim numbers(length)
`randomize + print before sorting
set cursor 0,0
print "Before bubble sort:"
for i=0 to length
numbers(i)=rnd(100)
print str$(numbers(i))
next i
`wait for key, but update
while inkey$()=""
sync
endwhile
cls
t#=timer()
while sort=0
gosub bubblesort
endwhile
finaltime#=timer()-t#
print "After bubble sort:"
for i=0 to length
print str$(numbers(i))
next i
print "Time taken (in milliseconds)"
print finaltime#
do
sync
loop
bubblesort:
sort=1
for i=0 to length-1
if numbers(i)>numbers(i+1)
temp=numbers(i)
numbers(i)=numbers(i+1)
numbers(i+1)=temp
sort=0
endif
next i
return
"That's not a bug, it's a feature!"
"Variables won't, constants aren't."