Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Implementing Bubble Sort Algorithm:
Following are the steps involved in bubble sort(for sorting a given array in ascending order):
1)Starting with the first element(index = 0), compare the current element with the next element of the array.
2)If the current element is greater than the next element of the array, swap them.
3)If the current element is less than the next element, move to the next element. Repeat Step 1
Example:
include <stdio.h>
void bubbleSort(int arr[], int n)
{
int i, j, temp;
for(i = 0; i < n; i++)
{
for(j = 0; j < n-i-1; j++)
{
if( arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[100], i, n, step, temp;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
return 0;
Following are the Time and Space complexity for the Bubble Sort algorithm.
1)Worst Case Time Complexity [ Big-O ]: O(n2)
2)Best Case Time Complexity [Big-omega]: O(n)
3)Average Time Complexity [Big-theta]: O(n2)
4)Space Complexity: O(1)
Advantages of bubble sort:
▪︎It is easy to implement
▪︎In the bubble sort, elements are swapped in place without using additional temporary storage, so the space requirement is at a minimum.