Page 251 - Learn To Program With Scratch
P. 251
Bubble Sort
BubbleSort .sb2 If you have a set of names, game scores, or anything else that you want to
show in a particular order—alphabetically, from largest to smallest, and
so on—you’ll have to sort your list. There are many ways to sort lists, and a
bubble sort is one of the simplest algorithms. (The name refers to how values
“bubble” up through the list to their correct positions.) In this section, we’ll
learn about bubble sort and write a Scratch program to perform this kind
of sort for us.
Let’s say that we need to sort the list of numbers [6 9 5 7 4 8] in descend-
ing order. The following steps illustrate how the bubble sort algorithm works.
1. We’ll start by comparing the first two elements in the list. Since 9 is
larger than 6, we can swap their positions, as shown below.
original list list after swapping the
first two elements
2. Now we can compare the second and third elements, which are 6 and 5.
Since 6 is larger than 5, the two numbers are already in order, and we
can move on to the next pair.
3. We’ll repeat this process to compare the third and fourth, fourth and
fifth, and finally the fifth and sixth elements. Take a look at the list
after these three comparisons, shown below.
Swap
No
Swap
Change
4. This pass of the bubble sort is over, but our list still isn’t in the right
order. We need to perform a second pass, starting from step one. Once
more, we’ll compare each pair of elements and swap them if needed.
Here’s the list after a second pass:
No
Swap
Change
No
Change Swap
No
Change
Lists 229
www.it-ebooks.info

