Python
Programming Exercises,
Gently Explained
131
Figure 42-1: The pattern of i and j’s movement: j starts after i and moves to the right, and when it
reaches the end, i moves right once and j starts after i again.
Notice the similarity between the movement of i and j to the nested for loops in Project #26
―Handshakes.‖ As the algorithm runs, j starts after i and moves to the right, and when it reaches the
end, i moves right once and j starts after i again.
If you look at
the overall range of i and j, you’ll see that i starts at index 0 and ends at the
second to last index. Meanwhile, j starts at the index after i and ends at the last index. This means
our nested for loops over the numbers list parameter would look like this:
for i in range(len(numbers) - 1):
for j in range(i, len(numbers)):
Inside the inner loop, the numbers at
indexes i and j are compared, and if the number at index
i
is larger than the number at index j, they are swapped. Figure 42-2 shows the state of a list [8, 2,
9, 6, 3]
as the bubble sort algorithm swaps the two numbers after being compared at each step.
Python Programming Exercises, Gently Explained
132
Figure 42-2: The steps of the bubble sort algorithm as it sorts [8, 2, 9, 6, 3].
At the end of these two nested for loops, the numbers in the list will have been swapped into
sorted order.
Dostları ilə paylaş: