Reorder

Reordering

As the previous assignment indicated, reordering a list is a very common occurrence within a computer program. Consider some of these common tasks:

  • Rearranging the apps on an iPhone
  • Sorting items in an online shop by “bestselling,” “price,” or “best reviews"
  • Rotating an image
  • Ranking search results

All of these tasks are essentially reordering a list of items so that it is displayed in a different way. We’ve output lists in different orders before now, but we have not actually altered a list’s contents so that they are stored in a different order. Examine this (possibly daunting) program:

This program reorders a list, but how? It’s not actually as complex as it looks at first glance. Some of the parts of this program are directly copied from programs we have dealt with previously. For example,

Code
Explanation
The highlighted section is just the framework for processing a list—going through each item in the list one after the other. For reference, see the previous “Process a List” activity. Compare the program there, which simply instructs Scratch to say each item in the list, to the highlighted blocks here.
Here, the highlighted section is the algorithm for swapping two items in a list. This is a direct application of the previous “Swaps” activity, only rather than swapping two singular variables with one another, we are swapping two list items. Compare these blocks with those in the previous activity. How are they the same? How are they different?
Finally, let’s examine the remaining blocks. We know that we are processing a list, swapping out some items with others, but which items are we swapping?
The highlighted blocks determine which items are swapped. indexOfBestSoFar holds the index of the tentative item to be swapped. checkHere is an index variable that is used to process everything in the list that has not been reordered. The highlighted loop starts in the unsorted part of the list of words and repeatedly checks if any/all of the items are alphabetically before the rest. By the time it reaches the end, the first word alphabetically is denoted by indexOfBestSoFar. It will be then swapped with the first item, and so on.

The real workhorse of the program is this block of code:

This comparison block is the portion of our program that determines that we want the listed to be sorted in alphabetical order. If we were to desire a different ordering, such as by length of [word], only this block would differ in our resulting program!

Experiment

Access the Reorder! project on the Scratch website and play around with it. Work with it to sort items in numerical order, reverse alphabetical order, and ordered by length of [word].

Describe each of the changes you made while experimenting (INCLUDING THE FAILED ATTEMPTS!), and indicate why they work the way they do.