DEV Community

loading...
Cover image for Bubble Sort Implementation in Python

Bubble Sort Implementation in Python

Deepak Raj
Skilled in Data Science, Machine Learning, Deep Learning, As Well As Web Development Knowledge. React ❤️ to encourage Author.
Updated on ・2 min read

Bubble sort is one of the simplest algorithms to start learning Data structures and algorithms. It's a comparison-based algorithm in which adjacent elements are compared and swapped in order. This algorithm is suitable for small dataset.

It's not a very widely used sorting algorithm but is more often used as a teaching tool to introduce the concept of sorting.

Time Complexity: O(n2)

Bubble Sort Implementation in Python

How does Bubble Sort work?

  • compare the first and the second element. If the first element is greater than the second element, they are swapped.

  • Now, Compare second and third elements. Swap them to get them in order.

  • Repeat the process until the last element.

  • In each iteration, the comparison takes place up to the last unsorted element.

  • The array is sorted when all the unsorted elements are placed at their correct positions.

gif image for math problems

Bubble Sort Implementation in Python

class BubbleSort:
    """ BubbleSort Algorithm Implementation in Python 3.0+

        arr: Unordered list
        output: Return list in ascending order.
        time complexity: O(n2)

        Example : 
        >>> sort = BubbleSort()
        >>> sort([4,2,6,5,9,8])
        [2, 4, 5, 6, 8, 9]"""

    def __init__(self):
        print("Bubble Sort Algorithm is Initialized")

    def __call__(self, arr):
        n = len(arr)
        for i in range(n):
            already_sorted = True
            for j in range(n - i - 1):
                if arr[j] > arr[j + 1]:
                    arr[j], arr[j + 1] = arr[j + 1], arr[j]
                    already_sorted = False
            if already_sorted:
                break
        return arr

sort = BubbleSort()
print(sort([10,9, 5, 11, 2]))
Enter fullscreen mode Exit fullscreen mode

Discussion (3)

Collapse
hanpari profile image
Pavel Morava

Are you sure this is Python? Feels like Java to me. May I ask why did you deem necessary to make BubbleSort class? Should not be standalone function enough?

Collapse
codeperfectplus profile image
Deepak Raj Author

Hey, I Like your sarcasm. But It's Python.
This series is for study purpose. I am trying to cover one or more concept in one article.

Like:- OOP + __CALL__ function and Bubble sort method.

and 2 nd I prefer Classes over functions

Collapse
hanpari profile image
Pavel Morava • Edited

Huh, dev.to scrapped my answer. I guess there is a bug in mobile version.

Nevermind, watch this instead

youtu.be/o9pEzgHorH0