In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.
This is my attempt in Python:
mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.
How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?
P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.
To explain why your script isn’t working right now, I’ll rename the variable
unsortedtosorted.At first, your list isn’t yet sorted. Of course, we set
sortedtoFalse.As soon as we start the
whileloop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we setsortedback toFalse.sortedwill remainTrueonly if there were no elements in the wrong order.There are also minor little issues that would help the code be more efficient or readable.
In the
forloop, you use the variableelement. Technically,elementis not an element; it’s a number representing a list index. Also, it’s quite long. In these cases, just use a temporary variable name, likeifor “index”.The
rangecommand can also take just one argument (namedstop). In that case, you get a list of all the integers from 0 to that argument.The Python Style Guide recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it’s more to get you accustomed to what Python code most often resembles.
To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say,
(badList[i+1], badList[i])is(3, 5)) and then gets assigned to the two variables on the left hand side ((badList[i], badList[i+1])).Put it all together, and you get this:
(I removed your print statement too, by the way.)