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
- Comparing pairs of adjacent elements.
- Swap position to each other if they exist in the wrong order.
- Repeat this process for all the elements until the entire array is sorted.
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 Case | O(n2) |
Best Case | O(n) |
Average Case | O(n2) |
Space Complexity | |
Worst Case | O(1) |
Applications of Bubble Sort
Bubble Sort is used in the following cases where
- the complexity of code does not matter
- a shortcode is preferred
Other Sorting algorithms:-
- Insertion Sort
- Selection Sort
- Merge Sort
- Counting Sort
- Bucket Sort
- Radix Sort
- Quick Sort
- Heap Sort
- Shell Sort
Related:
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.😎