Hexwell Hexwell - 1 year ago 74
Python Question

What is wrong with my sorting algorithm?

I am a beginner programmer and I've been trying to create my own sorting algorithm in Python, I don't understand why it outputs only some of the numbers that were present in the input. I put debug prints everywhere to understand the problem but still got nothing. The code should find and move to the final array the biggest number of the input array, and do that until the input array it's empty, but it seems to stop at some point. There was a person with a similar problem but the solution did not apply to me as well. This is the code:

array = [3, 6, 25, 4, 5, 24, 7, 15, 5, 2, 0, 8, 1] #just random numbers
output = []
while(len(array) > 0):
maximum = 0
for x in array:
maximum = max(maximum, x)
tempArray = []
for x in array:
temp = array.pop()
if(temp < maximum):
array = tempArray

Answer Source

The problem is here:

for x in array:
    temp = array.pop()

You're modifying the same list that you're iterating over. That's going to cause trouble.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download