List Sorting Algorithm in Python does not run
I am making a module called "dumbstuff" just as a hobby and can’t seem to identify the problem.The function is set to take in a list and an operator to sort the list in ascending order or descending order. When I run the function, a blank screen appears, I’ve been at it for a while and cannot figure out what’s wrong.
Here’s the sorting function in the "dumbstuff" module:
def sortlist(rawlist: list, operator: str, ifprint: bool): looped = 0 done = 0 index = 0 sortedList = [] while (done == 0): index = 0 looped = 0 #ascending sort if (operator == "<"): while (index < len(rawlist) - 1): if (rawlist[index] > rawlist[index + 1]): temp = rawlist[index] rawlist[index] = rawlist[index + 1] rawlist[index + 1] = temp looped += 1 if (looped == 0): done = 1 sortedList = rawlist #descending sort if (operator == ">"): while (index < len(rawlist) - 1): if (rawlist[index] < rawlist[index + 1]): temp = rawlist[index + 1] rawlist[index + 1] = rawlist[index] rawlist[index] = temp looped += 1 if (looped == 0): done += 1 sortedList = rawlist if (ifprint == True): print(sortedList)
and here is the code I am trying to run it through, it creates an array of 20 random integers,
import random import dumbstuff as ds array = [] index = 0 while (index < 20): array.append(random.randint(0, 20)) index += 1 ds.sortlist(array, "<", ifprint=True) input()
However, the code appears to never return and also never outputs anything to the screen.
You need to increment index
somewhere in your code.
Perhaps you could replace the while loop with a for loop.
#ascending sort if (operator == "<"): for index in range(len(rawlist) - 1): # Here. while (index < len(rawlist) - 1):
With this change, it appears to work https://repl.it/repls/SilentDelectablePrinter.