Introduction to Bubble Sort

Share

What is bubble sort?

Bubble sort is a basic exchange sorting algorithm. It is a comparison-based sorting algorithm in which
repetitive comparison of adjacent elements pairs is done and elements are swapped if they are in
the wrong order. This sorting technique is suitable only for small data sets.

How does bubble sort work?

Let’s say we have an unsorted array containing 5 elements.

1. Start with the first two elements from the leftmost side and sort them in ascending order by comparing them.
2. Then, compare the second and third elements and arrange them in ascending order by comparing them.
3. Then, compare the third and fourth elements and arrange them in ascending order by comparing them.
4. Then, compare the fourth and fifth elements and arrange them in ascending order by comparing them.
5. Repeat steps 1- 4 until no swaps are required.


Below is the visualization of the steps :

Bubble Sort : Pseudocode

int bubblesort( int array[], int n){
	int i,j,temp, switched= TRUE;
	
	for(i=0;i<n-1;i++){
		//outer loops controls the number of passes
		switched= FALSE;//no interchange have been made
		for(j=0; j<n-i-1; j++){
			//inner loop controls the function in each pass
			if( array[j] > array[j+1]){
				switched=TRUE;
				temp= array[j];
				array[j]= array[j+1];
				array[j+1]=temp;
			}
		}
	}
} //bubble end

Complexity Analysis of Bubble Sort

Best case: O(n)
Worst Case: O(n²)
Average Case: O(n²)

C program source code and online compiler: https://onlinegdb.com/bMyPlGEae

CSIT Bubble Sort Notes :


Share

One thought on “Introduction to Bubble Sort

Leave a Reply

Your email address will not be published.

%d bloggers like this: