This week, Hagrid is teaching us the selection sort, so shhhh! Since he really isn’t supposed to be teaching us any magic and not mention that he was expelled before he ever completed Hogwarts, it’s only natural the spell he’s about to teach us isn’t all that efficient. However, it still has it’s uses.

Selection Sort

Here’s your incantation:

For simplicity’s sake I split our incantation out into two functions since one function simply abstracts away a minor detail of the algorithm — swapping.

The swap function takes three parameters, first being the list, second being the first value to be swapped, and third being the second value to be swapped. It stores the element at list[first] in a temp variable before changing list[first] to equal list[second] . Finally list[second] will equal temp which was originally the value of list[first] before we changed it. The temp is necessary to store the original value. Otherwise, you’ll return a list with duplicate numbers.

As for the spell proper, what’s happening is quite simple.

With selection sort algorithms, you have an inner and outer loop. The outer loop starts at zero and sets the min value. This value starts off as 0.

The inner loop compares the rest of the array to value at list[min] , which starts out as 0. If the item at list[j] is greater than list[min] , we make j the new min .

Finally, we check to see if min has changed. It will have changed if it is no longer equal to i . If so, we call the swap function passing in list , i , and min as arguments. Then we repeat the loop, which is partly why this algorithm is so inefficient.

The algorithm will run through every element in a list no matter if it came partly sorted or not. It simply needs to run its course no matter what. There are even variations on this algorithm that swap no matter what, which really makes no difference seeing as the swap doesn’t make the algorithm any slower. It is the inner and outer loops themselves plus the way the algorithm iterates over the entire array no matter what that makes this incantation so sluggish.

Conclusion

But there you have it: a selection sort. Casting this spell is a little like firing Flipendo in slow motion, but it still does the job sometimes. Hope you enjoyed this week’s incantation, and next week I’ll be tackling a Breadth First Search (BFS). Cheers!