Python Forum
Question about Sorting a List with Negative and Positive Numbers
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about Sorting a List with Negative and Positive Numbers
#1
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)
Reply
#2
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]
>>>
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Random Generator: From Word to Numbers, from Numbers to n possibles Words Yamiyozx 2 1,370 Jan-02-2023, 05:08 PM
Last Post: deanhystad
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,249 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Sorting list - Homework assigment ranbarr 1 2,202 May-16-2021, 04:45 PM
Last Post: Yoriz
  Input validation for nested dict and sorting list of tuples ranbarr 3 3,841 May-14-2021, 07:14 AM
Last Post: perfringo
  Convert list of numbers to string of numbers kam_uk 5 2,935 Nov-21-2020, 03:10 PM
Last Post: deanhystad
  Positive and negative numbers in a row peterp 1 1,721 Oct-29-2020, 02:42 AM
Last Post: deanhystad
  insert() but with negative index naughtysensei 1 2,263 Oct-01-2020, 03:05 AM
Last Post: micseydel
  Return the sum of the first n numbers in the list. pav1983 3 3,958 Jun-24-2020, 03:37 AM
Last Post: deanhystad
  numbers in list - max value and average stewie 2 2,777 Apr-01-2020, 06:25 PM
Last Post: buran
  negative indices in lists Ironword 6 3,365 Jan-08-2020, 01:00 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020