Search code examples
pythonalgorithmbubble-sort

Bubble Sort help in python - ascending & descending order


So I am new to python and I have a project which requires us to go through a really long tuple list and we have to order the list in descending and ascending order. However, for both my functions I always get ascending order, WHAT IS WRONG? someone please help im really stressed out

def bubblesort_descending(tuple_list):
    j = len(tuple_list)
    made_swap = True
    swaps = 0
    while made_swap:
        made_swap = False
        for cnt in range (j-1):
            if tuple_list[cnt] < tuple_list[cnt+1]:
                tuple_list[cnt], tuple_list[cnt+1] = tuple_list[cnt+1], tuple_list[cnt]
                made_swap = True
                swaps = swaps + 1
    return swaps

Main Program:

elif choice ==  'd':
    unsorted = range(len(numbers))
    shuffle(unsorted)
    print ("Randomised tuple list generated:")
    print
    print (unsorted)

    swaps = bubblesort_descending (unsorted)
    print
    print ("heres the sorted list")
    print
    print (unsorted)
    print
    print (swaps, "swap(s) made")
    print

Solution

  • You need to convert that iterator to a list.

    unsorted = range(10)
    unsorted_list = list(unsorted)
    

    After this, your code will sort in descending order because you are making a swap if tuple_list[cnt] is less than tuple_list[cnt+1]. If you change the logical operator from "<"to ">" you will get ascending order because after changing, you will make swaps if tuple_list[cnt] is greater than tuple_list[cnt+1]

    By naming your list as tuple_list, it is kind of confusing. Because in python lists and tuples are different.
    What's the difference between lists and tuples?