Signup/Sign In

Python Program for Bubble Sort

Bubble Sort, operates by continuously exchanging neighboring items if they are in the wrong order. In this tutorial, we will perform the Bubble Sort operation to sort an array.

Bubble Sort - A basic Introduction

Bubble sort is a sorting algorithm in which two adjacent elements are compared and swapped until they are no longer in the desired order. In this operation, each element of the array moves to the end in each iteration, similar to how air bubbles rise to the surface of the water.

Let us have a rough understanding of bubble sort:

  1. Compare and Swap: - Compare the first and second items starting with the first index. The first and second elements are switched if the first is bigger than the second. Compare the second and third items now. If they aren't in the right sequence, swap them. The procedure continues until the last item is added.
  2. Remaining Iteration: - For the remaining iterations, the same procedure is followed. The biggest element among the unsorted items is placed at the conclusion of each iteration.
  3. The result after each operation is a sorted array.

For better understanding let's have a look at the diagram below:

Bubble-Sort

Algorithm

As of now, we have a rough understanding of how merge sort is performed. For better understanding let's dive deep into the algorithm followed by the code:

  1. Create a Bubble_Sort() function
  2. Pass a parameter array to the function
  3. Create a loop to access each array
  4. Create a loop to compare array elements
  5. Compare two adjacent elements
  6. Swap elements if not in order
  7. The result will be a sorted array
  8. Print the array

Program for Bubble Sort

As discussed above in the algorithm, let us now dive into the programming part of the Bubble Sort operation influenced by the algorithm.

def bubbleSort(array):
  # access each element
  for a in range(len(array)):
     # compare array elements
    for b in range(0, len(array) - a - 1):
      # compare 
      if array[b] > array[b + 1]:
          
        # swapping elements
        temp = array[b]
        array[b] = array[b+1]
        array[b+1] = temp

#driver code
array = [5, 4, 2, 1, 3]
print("The original array is: ", array)

bubbleSort(array)
print('The Sorted Array is: ', array)


The original array is: [5, 4, 2, 1, 3]
The Sorted Array is: [1, 2, 3, 4, 5]

Conclusion

In this tutorial, we have performed a Bubble Sort operation in python to sort an array. Bubble sort is used when complexity doesn't matter. The best-case complexity of bubble sort is O(n) and worst snd average-case complexity is O(n2), the space complexity of bubble sort is O(1).