Bubble Sort

Last updated on September 4th, 2023 at 09:46 pm

Here, We will learn about bubble sort in C, their algorithm, implementation in C, time & space complexity and their applications.

What is Bubble Sort?

Bubble Sort is the simplest sorting algorithm. It compares all the elements one by one and sorts them based on their values.

The algorithm is based on idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.

Bubble Sort is simple but having high time complexity.

It is called Bubble sort, because with each iteration the smaller elements in the list bubble up towards the first place, just like a water bubble rises up to the water surface.

Algorithm

  1. Comparing pairs of adjacent elements.
  2. Swap position to each other if they exist in the wrong order.
  3. Repeat this process for all the elements until the entire array is sorted.
bubble sort, bubble sort in c
Example

Implementation of Bubble Sort

Program Code in C :-

#include<stdio.h>

void bubblesort(int array[], int n)
{
  //run two loop one for element access and other for comparision
  for(int i=0; i<n-1; i++)
  {
    for(int j=0; j<n-i-1; j++)
    {

      //to sort in descending order
      if(array[j] > array[j+1])
      {

        //swap if greater is at the rear position
        int temp = array[j];
        array[j] = array[j+1];
        array[j+1] = temp;
      }
    }
  }
}

//function to print the array
void printarray(int array[], int n)
{
  for(int i=0; i<n; i++)
  {
    printf("%d ",array[i]);
  }
  printf("\n");
}

//Driver Code
int main()
{
  int data[] = {23, 17, 5, 90, 31};
  int n =sizeof(data)/sizeof(data[0]);
  bubblesort(data, n);
  printf("Sorted Array : ");
  printarray(data, n);
}

Output :-

Time and Space Complexity of Bubble Sort

Time Complexity
Worst CaseO(n2)
Best CaseO(n)
Average CaseO(n2)
Space Complexity
Worst CaseO(1)

Applications of Bubble Sort

Bubble Sort is used in the following cases where

  1. the complexity of code does not matter
  2. a shortcode is preferred

Other Sorting algorithms:-



Want to Contribute:-

If you like “To The Innovation” and want to contribute, you can mail your articles to 📧 contribute@totheinnovation.com. See your articles on the main page and help other coders.😎

Scroll to Top