Search code examples
pythonbubble-sort

How can i get the input from the user and display the sorted list


How can i get 8 input from the user and sort it to ascending order using bubble sort algorithm i tried this code but the output is wrong the array is not in the sorted way and there is no errors the output i'm getting is [1]

def sort(num):

    for i in range(len(num)-1,0,-1):
        for j in range(i):
            if num[j]>num[j+1]:
                temp = num[j]
                num[j] = num[j+1]
                num[j+1] = temp

for t in range (8):
    nums=int(input("Enter Number: "))
    num=[nums]
sort(num)

print(num);

Solution

  • Actually, you are doing wrong while taking input, each time the user input is taken num list is updated with new user input. I mean to say:

    user enter: 4

    num = [4]

    next iteration, user enter : 5

    now num becomes num = [5]

    Hence, you have to do following modification, that is use append method of list in for loop.

    num = []
    for i in range(8):
        num=int(input("Enter Number: "))
        nums.append(num)