Python Forum

Full Version: Question about Sorting a List with Negative and Positive Numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I'm trying to sort this "List' of values that contains both negative and positive numbers. I'm trying to sort in numerical order from least to the greatest value using a double for loop and swapping variables. However, I ran into some errors when running my code, and I think it's because of the negative values in the "List" array. How do I get around this problem?


Here is my Python code that I have written so far:
numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]

length_numbers = len(numbers)

for i in numbers:
  for j in range (0, length_numbers):
    
    if numbers[j] > numbers[j+1]:
      temp = numbers[j]
      numbers[j] = numbers[j+1]
      numbers[j+1] = temp

print(numbers)
just use:
>>> numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
>>> numbers.sort()
>>> numbers
[-63.1, -11.9, -4.8, 0, 11.5, 15.9, 23.5, 28.3, 32.6, 67.4, 79.4, 80.0]
>>>
But if you are trying to learn about writing a bubble sort, your error is in line 6. Since you are comparing numbers[j] to numbers[j+1], you will get an index error when j is length_numbers and you try to access numbers[j+1]. Change line 6 to
for j in range (0,length_numbers-1):
and it works just fine.