Deus Ex
Deus Ex

Reputation: 111

sorting algorithm doesn't produce correct output

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

Upvotes: 0

Views: 32

Answers (1)

Aryerez
Aryerez

Reputation: 3495

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]

Upvotes: 1

Related Questions