New Tutorials:   KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL  
   Algorithm  Bubble Sort  Python  
   Technology    Programming

(Efficient) Bubble Sort in Python

 MARCH 5, 2020   by HIMANI56

In the previous tutorial, we learned a simple implementation of Bubble Sort in python, where we compare every element with every other element and swap their positions to ultimately sort the array or the list of numbers.

But, in the majority of the cases, while using bubble sorting technique, the array gets sorted before the completion of all the iterations. So why bother wasting time, waiting for our loops to end?

So in the code below, we have tweaked the original bubble sort algorithm and introduced a flag to check if swapping is happening, if not, we break out of the loop, because the array is sorted.

We have a detailed tutorial covering How Bubble Sort Works, and we strongly recommend you go through it to understand the functioning of the bubble sort algorithm, before going over the code below.

We have used python list for implementing the bubble sorting technique. You can change the code, as you like.


Subscribe and receive amazing posts directly in your inbox.