Search code examples
pythonsortingwords

Python Bubble sort Words


I'm new to python im looking for a code to bubble sort a list of words.

mylist = [12, 5, 13, 8, 9, 65]

def bubble(badList):
    length = len(badList) - 1
    unsorted = True

    while unsorted:
        for element in range(0,length):
            unsorted = False
            if badList[element] > badList[element + 1]:
                hold = badList[element + 1]
                badList[element + 1] = badList[element]
                badList[element] = hold
                print badList
            else:
                unsorted = True

print bubble(mylist)

this code does it with numbers i want one that does it with words. Thanks


Solution

  • One of the many cool things about Python is that equality and comparison operators work for strings just as they do with numbers. For example, how to compare that two numbers are the same?

    7 == 7 # true!
    

    How about two strings?

    "Hello world".equals("Hello world") // Java...
    
    "Hello world" == "Hello world" # Python!
    

    Now to comparators. Python uses lexicographic ordering to compare strings. Basically, it looks at the first character from each string and says, "which is bigger?". If they are the same, it continues on down the string. So a few examples:

    "ABC" > "BAC" # false, because the character B is greater than A
    "AAAB" < "AAAC" # true, because the character B is less than C
    

    So, your code will work no matter if mylist is comprised of ints or of strings.