Reputation: 19
def bbsort(list1):
for passnum in range(len(list1)-1,0,-1):
for i in range (passnum):
if list1[i]>list1[i+1]:
temp =list1[i]
list1[i] = list1[i+1]
list1[i+1] = temp
This is code for a bubble sort, but what is the use of -1,0,-1
in the while
condition?
Upvotes: 0
Views: 6114
Reputation: 3279
The first -1 subtracts 1 from the length of the input list because the indexes start from 0, not 1. The 0 is the start number(only neccesary to get to the next parameter). The 2nd -1 is the step so that tells it to move backwards through the range.
Example: range(5, 2, -1) is [5, 4, 3]
equal to range(start, stop, step)
Upvotes: 1
Reputation: 1123410
You are looking at arguments to the range()
function; the numbers set up the range to start at the list length, minus one, then stepping down to 1 (the end point is not included in the range).
So there are 3 arguments, the first is len(list1) - 1
, the second is 0
and the third is -1
.
Say the list is length 5, then range(5 - 1, 0, -1)
will produce a list with 4, 3, 2, and 1:
>>> list(range(4, 0, -1))
[4, 3, 2, 1]
The for
loop steps over these values:
>>> for i in range(4, 0, -1):
... print(i)
...
4
3
2
1
The for
loop assigns these numbers to passnum
, and the next nested loop uses that to create a new range()
. The first time, that inner range will go from 0
to len(list1) - 1
(exclusive), the next time from 0
to len(list1) - 2
, etc, until the last time, when it'll run from 0
to 1
, always excluding the stop index. For a list of length 5, that means the inner loop first assigns 0, 1, 2, 3 to i
, then 0, 1, 2, then 0, 1, then 0.
The code is missing an opportunity to use Python sequence assignment to swap to elements:
def bbsort(list1):
for passnum in range(len(list1) - 1, 0, -1):
for i in range (passnum):
if list1[i] > list1[i + 1]:
list1[i], list1[i + 1] = list1[i + 1], list[i]
Upvotes: 9