0
def sort(nums):
    finish = False
    while finish == False:
        finish = True
        for i in range(len(nums)-1):
            if nums[i] > nums[i+1]:
                t = nums[i]
                nums[i] = nums[i+1]
                nums[i+1] = t           
                finish = False

                print(nums)     
    return nums

output

9 is clearly not greater than 101, so i dont know why it keeps getting swapped

2
  • 3
    You are sorting strings, not integers. As a string '9' is greater than '101'. Commented Nov 17, 2019 at 2:06
  • Variables should be compared to boolean literals using is, not ==. While we’re on the subject, finish == False is just not finish. Commented Nov 17, 2019 at 7:54

1 Answer 1

1

As stated in the comments, the sorting problem comes from the fact that your input is a list of strings and not ints. You can easily transform the values with a list comprehesion.

Two more comments: 1) Unlike other programming languages, in python you don't need to use a temporary variable to switch the values of two variables, and you can do it in 1 line instead of 3. 2) It's more accepted to use while True structure without pre-defining a special variable (e.g "finish") before the loop, and to use a break clause to get out of the loop.

So here is the fixed and modified code:

def sort(nums):
    nums = [int(n) for n in nums] #This is the neccesary line to fix the bug you are having
    while True:
        finish = True
        for i in range(len(nums)-1):
            if nums[i] > nums[i+1]:
                nums[i], nums[i+1] = nums[i+1], nums[i]
                finish = False
                print(nums)
        if finish:
            break
    return nums
l = ['1', '101', '9', '808', '54']
sort(l)

Output:

[1, 9, 101, 808, 54]
[1, 9, 101, 54, 808]
[1, 9, 54, 101, 808]    

Out[17]:

[1, 9, 54, 101, 808]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.