Ahmetcan Akkoyun
Ahmetcan Akkoyun

Reputation: 21

Bubble sort query

I don't understand what is happening on line 2, with the "-1, 0 , -1". Why does it need to do this, and what does the zero represent?

I have run the code, when I removed the "-1, 0, -1" part and it didn't sort the list. I don't understand why it is such a crucial part of code

def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1): #line 2
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

alist = [54,26,93,17,77,31,44,55,20]
bubbleSort(alist)
print(alist)

Upvotes: 2

Views: 87

Answers (3)

blue note
blue note

Reputation: 29099

That has nothing to do with the algorithm. range has 3 arguments

  • from
  • to
  • step

In this case, this means

  • start from the last element (index=N-1)
  • continue until the second (index=0)
  • step=-1 (to go backwards)

Upvotes: 3

Aidenhjj
Aidenhjj

Reputation: 1289

As comments suggest, if you'd googled the docs for range, you might have worked things out. Your line:

range(len(alist)-1,0,-1)

Means the range starts at the end of the list (which is the length, minus 1, since lists are 0 indexed), and ends at 1 (one before 0), with steps of -1 (backwards).

Upvotes: 0

Julian Minde
Julian Minde

Reputation: 166

Those are arguments to range(start, stop, sep) (https://docs.python.org/3/library/functions.html#func-range) In your case you create a range that starts with the length of your list -1 (len(alist)-1), and count to 0, by taking steps of -1.

Upvotes: 0

Related Questions