Search code examples
pythonpython-3.xbubble-sort

TypeError: must be str, not int in bubble sort


I'm having this kind of error in my Python code in sorting algorithm (bubble sort)

Traceback (most recent call last): File "D:\CSC\PYTHON SAMPLE CODES\bubstepbystep.py", line 13, in nlist = nlist + i TypeError: must be str, not int

I could not figure out what's happening inside. Please help me.

import time

nlist = input("Enter series of numbers: ")
swap = len(nlist)
qty = len(nlist)
print("Original:", nlist)


for x in range(qty - 1):
    for i in range(swap - 1):  #swap
    if nlist [i] > nlist [i+1]:
        temp = nlist [i]
        nlist = nlist + i
        nlist [i+1] = temp

        print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist)
        time.sleep(3)
    else:
        print("\nSwapping Index:", i,"and", i+1)
        time.sleep(3)
        print("Nothing to swap, skipping . . .")
        time.sleep(3)

swap -= 1

Solution

  • Your problem is your input, I think: map it to proper integers and things look much better. Also, your swap code was not correct:

    import time
    
    nlist = list(map(int, input("Enter series of numbers: ").split()))
    nlist 
    swap = len(nlist)
    qty = len(nlist)
    print("Original:", nlist)
    
    for x in range(qty - 1):
        for i in range(swap - 1):  #swap
            if nlist [i] > nlist [i+1]:
                temp = nlist [i]
                print(temp)
                nlist [i] = nlist [i+1]
                nlist [i+1] = temp
    
                print("\nSwapping Index:", i,"and", i+1, "\n\rNew list:", nlist)
                time.sleep(3)
            else:
                print("\nSwapping Index:", i,"and", i+1)
                time.sleep(3)
                print("Nothing to swap, skipping . . .")
                time.sleep(3)
    
    swap -= 1
    
    print("Final:", nlist)