Bubble Sort Algorithm Example

Bubble sort algorithm 

How Bubble Sort Works?

  1. Starting from the first index, compare the first and the second elements.If the first element is greater than the second element, they are swapped.

    Now, compare the second and the third elements. Swap them if they are not in order.

    The above process goes on until the last element.
    Bubble Sort Steps
  2. The same process goes on for the remaining iterations. After each iteration, the largest element among the unsorted elements is placed at the end.

    In each iteration, the comparison takes place up to the last unsorted element.

    The array is sorted when all the unsorted elements are placed at their correct positions.
    Bubble Sort Steps

    Bubble Sort Steps

    Bubble Sort steps
     // Bubble sort in C Program
    
    #include <stdio.h>
    
    void bubbleSort(int array[], int size)
    {
      for (int step = 0; step < size - 1; ++step)
      {
        for (int i = 0; i < size - step - 1; ++i)
        {
          // To sort in descending order, change">" to "<".
          if (array[i] > array[i + 1])
          {
            int temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
          }
        }
      }
    }
    void printArray(int array[], int size)
    {
      for (int i = 0; i < size; ++i)
      {
        printf("%d  ", array[i]);
      }
      printf("\n");
    }
    int main()
    {
      int data[] = {-2, 45, 0, 11, -9};
      int size = sizeof(data) / sizeof(data[0]);
      bubbleSort(data, size);
      printf("Sorted Array in Ascending Order:\n");
      printArray(data, size);
    }

Comments