Bubble Sort in C

With the help of sorting we arrange elements in some logical order.

Bubble Sort

Let us arrange elements in ascending order.

Steps involved:

  1. Compare 1st element with 2nd.
  2. If first element is greater than 2nd element then swap them.
  3. Compare 2nd element with 3rd.
  4. If 2nd element is greater than 3rd then swap them.
  5. Compare 3rd element with 4rth and so on.

On first iteration we get the largest element bubbled up. Similarly, on second iteration we get 2nd last item bubbled up.

How to calculate the length of an array

  • sizeof(a) will return the total bytes allocated to an array.
  • To get the length divide it by size of any element.
 int len = sizeof(a)/sizeof(a[0])
  1. We need two loop.
  2. We want n items to get bubbled up.
  3. In each iteration we are comparing each element with the next element so we need (n-1) comparisons each time.
#include <stdio.h>
#include <string.h>

  int a[] = {23, 34, 12, 67, 5, 9};
  int len = sizeof(a)/sizeof(a[0]), temp, i, j;
  for(j = 0;j<len;j++){
  for(i =0; i<len-1;i++){
          temp = a[i];
          a[i] = a[i+1];
          a[i+1] = temp;

    printf("%d\n", a[i]);


Complexity: We iterate n times no matter in which order elements are arranged in array. In each iteration we do (n-1) comparisons.

So the best, worse and average time would be O(n^2).