Leo watched an extremely good TedEd about sorting algorithms, and wanted to try it out himself, so we wrote a simple bubble sort in Python, and we deployed it through the PythonCraft API to run in MineCraft. This turned out to be more fun and educational than I thought it was going to be.
To begin with, here’s the code (slightly cleaned up for display here; you’ll have to add the right imports, for example):
Unsurprisingly, we had the longest discussion about why you need the “Hold” variable in the swap step(s). There are two errors in this code, that I’ll reveal below. (The highly motivated reader can try to figure these out; Actually, any semi-competent programmer can probably guess what the errors are without even looking at the code!) Regardless, it does the basic job.
So, it’s actually extremely cool when it runs, because you can watch the sort in action, and actually chase down the sort front! Here are a couple of videos of us doing that:
(Note the sheep on the blocks!)
You can see (and I mention) one of the bugs in the video: The “Obi wan” (Off by One) error, which leaves on of the blocks unsorted at the far end of the array.
The other bug is more subtle, until I point it out: We actually intended to sort by rainbow order (ROYGBIV), but that would have required another dereference, and when I tried to explain that, it went right over Leo’s head, him already being well snowed by the Hold/Swap problem, so I simply let it go. As a result, it’s actually sorting by whatever the color codes happen to be in MineCraft, which seem to be random (or at least I can’t tell what the logic is that relates MC color IDs to rainbow order).