Coding for Kids

Arrays: Sorting Elements

Sometimes you just need an array to keep track of items on a list. Other times, you want to sort those items. There's a default way to do this, but you can also develop your own sorting method to really control how your lists are sorted.

Sorting an array with .sort()

There is a default sort method for arrays, which will sort items from low to high values.

Numbers are easily sorted. Strings are sorted based on the character codes of each string. Uppercase characters have lower values than lowercase and so they're sorted first.

This does change the array.

Creating a sorting function.

There is a way to create your own sorting method. It requires creating a sorting function, in which you tell it how to sort by comparing two values.

If the sorting function returns a negative like -1, it shifts an item toward the front.
If it's positive like 1 it shifts the item toward the end.
If it's 0 the item doesn't move.

Let's say you're making a game and you want to sort monsters based on their agility scores to figure out in what order they should attack. The basic .sort() method can't handle it because it doesn't know what you want to sort by. This a – b process returns a list in ascending order.

Here are the monsters we want to sort:

Here's the agility sorting method we're using:

Here's what's returned. Check out the order they're in:

 

Let's sort by hp this time:

If we wanted, instead we could sort by hp, but let's put the highest hp at the front of the list. Notice that this has b – a for descending order.

We'll sort the same monster set as before.

Here's the output. Check out the order now:

 

Let's sort this set of monsters:

We can get a lot more complex if we need to! Like, what if you wanted to sort by name and, if the names are the same, then by agility?

Here's the sorting method we're using:

Here's the output. Check out the order now:

Whoa! What's going on? Well first, it checks to see if each name is different. When we did agility and hp, we could just subtract. But the name is a word so we have to check for greater than, less than, and equal to in order to sort them. Alphabetically, e is less than r, and so on.

If the names are the same, the else block then sends back the sort for agility. Could you figure out how to add an additional sort for hp if the name and agility are the same? Give it a try!

I hope that was more than just sort of fun!

—Dr. Wolf