Bubble Sort Algorithm in Python

In this post, I provide a code that performs a bubble sort in python. Before using, I recommend checking the indentations, as this code was written in a standard text-editor. This python bubble-sort algorithm should be fine, though. This python algorithm was written using the example output in Reference 1. One can compare the output of this program to the content on that page, to confirm that this code is working as expected.

 

PYTHON BUBBLE SORT ALGORITHM:

x = [5,1,4,2,8]

 

def bubble_sort(a):

      sorted_list = []

      for index,value in enumerate(a):

            sorted_list.append(value)

 

      counter = 0

      number_of_comparisons  = 0 

      number_of_swaps = 0

      for index, value in enumerate(a):

              if index != len(a) – 1:

                         number_of_comparisons = number_of_comparisons + 1

                         if value > a[index+1]:

                                 number_of_swaps = number_of_swaps + 1

                                 sorted_list[index] = a[index+1]

                                 sorted_list[index+1] = value

                                 print(“sorted list”, sorted_list, “counter”,counter)

                         return sorted_list,1,number_of_comparisons,number_of_swaps

              

       print(“array is sorted!”,sorted_list)

       return sorted_list,0,number_of_comparisons,number_of_swaps

              

     

total_number_of_comparisons = 0

total_number_of_swaps = 0

output = x   

my_variable = 1 # not sorted, 0 means sorted

while my_variable != 0:

          output,my_variable,number_of_comparisons ,number_of_swaps= bubble_sort(output)

          total_number_of_comparisons = total_number_of_comparisons+number_of_comparisons   

          total_number_of_swaps = total_number_of_swaps + number_of_swaps

print(“total number of comparisons”, total_number_of_comparisons)

print(“total number of swaps”, total_number_of_swaps)

 

References:

[1] https://www.geeksforgeeks.org/bubble-sort/

Christina Daniel

I am a research assistant in theoretical physics. This website, derive-it.com, serves to organize my ongoing learning and research as well as to provide a resource to other learners around the world.

Leave a Reply