How does Bubble Sort Work?

Let us understand the working of bubble sort with the help of the following illustration:

Input: arr[] = {6, 0, 3, 5}

First Pass: 

The largest element is placed in its correct position, i.e., the end of the array.

Bubble Sort Algorithm : Placing the largest element at correct position

Second Pass: 

Place the second largest element at correct position

Bubble Sort Algorithm : Placing the second largest element at correct position

Third Pass:

Place the remaining two elements at their correct positions.

Bubble Sort Algorithm : Placing the remaining elements at their correct positions

  • Total no. of passes: n-1
  • Total no. of comparisons: n*(n-1)/2

Bubble Sort – Data Structure and Algorithm Tutorials

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

Similar Reads

Bubble Sort Algorithm

In Bubble Sort algorithm,  traverse from left and compare adjacent elements and the higher one is placed at right side. In this way, the largest element is moved to the rightmost end at first. This process is then continued to find the second largest and place it and so on until the data is sorted....

How does Bubble Sort Work?

Let us understand the working of bubble sort with the help of the following illustration:...

Implementation of Bubble Sort

Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap....

Complexity Analysis of Bubble Sort:

Time Complexity: O(N2)Auxiliary Space: O(1)...

Advantages of Bubble Sort:

Bubble sort is easy to understand and implement.It does not require any additional memory space.It is a stable sorting algorithm, meaning that elements with the same key value maintain their relative order in the sorted output....

Disadvantages of Bubble Sort:

Bubble sort has a time complexity of O(N2) which makes it very slow for large data sets.Bubble sort is a comparison-based sorting algorithm, which means that it requires a comparison operator to determine the relative order of elements in the input data set. It can limit the efficiency of the algorithm in certain cases....

Some FAQs related to Bubble Sort:

What is the Boundary Case for Bubble sort?...

Contact Us