Summary: In this tutorial, you will learn what is Bubble Sort algorithm and how to sort an array using the Bubble Sort algorithm in C, C++, and Java.

Introduction to Bubble Sort Algorithm

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.


Bubble sort compares two adjacent elements of an array and swaps them if they are in the wrong order.

It repeats this process for each element in the loop until the whole array gets sorted.

Bubble Sort – compare and swap wrong order elements

Here, for i=0 iteration, 4 and 1 were found in the wrong order, so they are swapped.

For i=1 iteration, 2 and 1 were found in the wrong order, so this time 2 and 1 are swapped.

For an array of size equal to n, a maximum of n repetition is enough to sort the array using the bubble sort technique.

Bubble Sort Algorithm

Note: This bubble sort algorithm is for sorting an array in ascending order.

After each iteration, the largest element of the unsorted partition gets shifted to the end, so indexOfLastUnsortedElement can be written as sizeOfArray-i, where i is the iteration count.

Here is the implementation of the bubble sort algorithm in C, C++, and Java.





Bubble Sort in C++

The most important step in the bubble sort is the swapping of the two elements. The code in the program used for swapping element is:

Note: In swapping if we would not have stored 1st variable’s value into a temporary location then we could have lost that value on updating it with the 2nd variable’s value.

Bubble Sort Overview

  • In place Algorithm – We don’t require an extra array to sort an array.
  • O(n²) time complexity – quadratic.
  • Becomes insufficient as array sizes grow large.

In this tutorial, we learn’t what is bubble sort algorithm and how to use bubble sort algorithm to sort any liear data structure such as an array.

Leave a Reply

5 × one =