DEV Community

Cover image for Bubble Sort Implementation in Python
Deepak Raj
Deepak Raj

Posted on • Updated on

Bubble Sort Implementation in Python

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

Top comments (0)