var/list/items=newlist(/obj/sword{icon='sword.dmi';}, /obj/knife{icon='knife.dmi';}, /obj/gun{icon='gun.dmi';}, /obj/shield{icon='shield.dmi';}, /obj/spear{icon='spear.dmi';})
obj
var/gold=0
sword
gold=10
knife
gold=2
gun
gold=15
shield
gold=12
spear
gold=7
mob/verb/order_items()
var
i
j
temphold
for(i=1, i<items.len, i++)
for(j=i+1, j<items.len+1, j++)
var
obj
a=items[i]
b=items[j]
if(a.gold>b.gold)
temphold=items[i]
items[i]=items[j]
items[j]=temphold
var/
obj
a=items[1]
b=items[2]
c=items[3]
d=items[4]
e=items[5]
src << "The items in order from least to greatest gold cost are [a], [b], [c], [d], [e]"
Congratulations, you implemented Bubble Sort, the least efficient sorting algorithm out there.
|
I will hardly tackle sorting algorithms, but a better version of your sort would be quicksort. There are better sorting algorithms out there, though, and sorting is a very large topic I'd rather not go too deeply in.
What quicksort does, is break a list in half, then divide and conquer with a marching sort. proc There are some optimizations to this sort I haven't applied. Somtimes, it's best to eject out to an insertion sort once your pivot points get clustered enough, but that's a totally different post. |
There's also always something like this: Making sure your lists are always in order.
I use a tree search to place new elements. You can set up your own value heuristic, and create a means of backing the list against useful data easily enough. orderedlist Of course, it's really only meant to be used for things that don't have a lot of changes. Best to avoid sorting until the end if you are going to add a huge number of values to something, or if the value heuristic is unstable. |
for(j=i+1, j<items.len+1, j++)
What.