简体   繁体   中英

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

As stated in the comments, the sorting problem comes from the fact that your input is a list of string s and not int s. 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 (eg "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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM