# Bubble Sort Program, Algorithm & their Time Complexity

Bubble Sort program, Algorithm & their time complexity. Write a program to implement a bubble sort algorithm. What’s the time complexity of bubble sort algorithm ?

In this tutorial, We are going to learn about bubble sort algorithm and their implementation in various programming languages.

## Bubble Sort

Bubble sort algorithm work by comparing each pair of adjacent elements and switching their positions if necessary. It repeats this process until all the elements are sorted.

The average and worst-case time complexity of bubble sort is – O(n2)

## Bubble Sort Algorithm

2. Swap the position of adjacent elements if it’s in wrong order.

3. Repeat the above process until all the elements are sorted.

Subscribe Our Tutorials

To understand the bubble sort algorithm, let’s take an example of an unsorted array. This array needs to be sorted in ascending order.

Array arr[] = {1, 5, 3, 2}

STEP 1 – In the first step, 1 is compared with 5.  Since 1 is smaller than 5 so the position remains unaffected . Now 5 is compared with 3. 3 is smaller than 5, so the position is swapped. Similarly, 5 is compared with 2. 2 is smaller than 5, so the position is swapped.

arr[] = {1, 3, 2, 5}

STEP 2 – In the second step, 1 is compared with 3. 1 is smaller than 3 so the position remains unaffected. Now 3 is compared with 2. 2 is smaller than 3, so the position is swapped.

arr[] = {1, 2, 3, 5}

STEP 3 – In the third step, All the elements of an array is already sorted, so nothing gets changed in this step.

arr[] = {1, 2, 3, 5}

## Bubble Sort Program in C

We have understood how bubble sort works. Let’s implement them in C.

## Bubble Sort Program in PHP

### Conclusion

Bubble sort algorithm is very easy to implement but it’s not efficient for large data sets.