Bubble Sort Algorithm

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.

How does Bubble Sort Work?

Suppose we are trying to sort the elements in ascending order.

1. First Iteration (Compare and Swap)

  1. Starting from the first index, compare the first and the second elements.
  2. If the first element is greater than the second element, they are swapped.
  3. Now, compare the second and the third elements. Swap them if they are not in order.
  4. The above process goes on until the last element

Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap.

#include <stdio.h>
int main()
{
int arr[100], size, i, j, swap;

printf(“Enter Array size: “);
scanf(“%d”, &size);

printf(“Enter %d integers: “, size);

for (i=0; i<size; i++){
scanf(“%d”, &arr[i]);
}
for (i=0 ; i<size-1; i++)
{
for (j=0; j<size-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap = arr[j];
arr[j] = arr[j+1];
arr[j+1] = swap;
}
}
}
printf(“\nSorted list in ascending order: \n”);
for (i=0; i<size; i++)
printf(“%d “, arr[i]);

return 0;
}

Complexity Analysis of Bubble Sort:

Time Complexity: O(n2)
Auxiliary Space: O(1)

Advantages of Bubble Sort:

Disadvantages of Bubble Sort:

Leave a Reply

Your email address will not be published. Required fields are marked *