Bubble Sort Program, Algorithm & their Time Complexity

Bubble Sort program, Algorithm & their time complexity.In this tutorial, We are going to learn about bubble sort algorithm and their implementation in various programming languages.

In this tutorial, we are going to cover following things

  • What is Bubble Sort?
  • Bubble sort algorithm & it’s time complexity
  • Bubble sort program in C & C++
  • Bubble sort implementation in PHP

 

What is Bubble Sort?

Bubble sort is a sorting algorithm, It works 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

Bubble Sort Algorithm

Bubble Sort Algorithm

1. Compare two adjacent elements.

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

C program to swap two number without using third variable

C program to swap two numbers using third variable

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

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

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.

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.

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

 

Bubble Sort Program in C

We have understood how bubble sort works. Let’s write a bubble sort program in C. In this program, We take an input array from a user (unsorted array) and then sort this array.

 

C++ Program to Implement Bubble Sort

We have written a C code. In this example, we are going to write a C++ code to implement this sorting algorithm.

 

Bubble Sort Program in PHP

Let’s write a PHP code to implement bubble sort algorithm.

Conclusion

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

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.