Search code examples
pythoninputbubble-sort

Bubble sort algorithm input not working (Python)


this is a question about some of the handling of arrays in python.

I have the following code that reads an array of numbers from the variable sorted:

print("Original: ",sorted)

for largeRepeat in range(0,len(sorted)):
    for Repeat in range(0,len(sorted)-1):
        Number1 = sorted[Repeat]
        Number2 = sorted[Repeat + 1]
        if Number1 > Number2:
            sorted[Repeat] = sorted[Repeat+1]
            sorted[Repeat+1] = Number1



print("Sorted: ",sorted)

Now, the problem I have is that I can assign the array some values in 2 different ways, hard-coded into the program:

sorted = [1,11,22,2]

or by user input, splitting the numbers provided by using split():

inputs = input("Enter numbers as comma (,) separated values: ")
ToSort = inputs.split(",")
sorted = ToSort

If I use the permanent method, the program correctly returns:

Original:  [1, 11, 22, 2]
Sorted:  [1, 2, 11, 22]

but, if I use the user input, the program incorrectly returns:

Original:  ['1', '11', '22', '2']
Sorted:  ['1', '11', '2', '22']

Could anyone please provide any insight into why this might be happening, I've tried running the program multiple times and isolated it to this specific section.

I've also noticed that it returns the numbers in the user input as strings of text but I don't see how this could cause a problem. (Sorry, i'm quite new to this!)

Thanks in advance!

Edit: Thank you, this has been solved!


Solution

  • You need to cast each input as int

    ToSort = list(map(int, inputs.split(",")))