Back to Course

Algorithm

0% Complete
0/82 Steps
  1. Getting Started with Algorithm
    What is an Algorithm?
  2. Characteristics of Algorithm
    1 Topic
  3. Analysis Framework
  4. Performance Analysis
    3 Topics
  5. Mathematical Analysis
    2 Topics
  6. Sorting Algorithm
    Sorting Algorithm
    10 Topics
  7. Searching Algorithm
    6 Topics
  8. Fundamental of Data Structures
    Stacks
  9. Queues
  10. Graphs
  11. Trees
  12. Sets
  13. Dictionaries
  14. Divide and Conquer
    General Method
  15. Binary Search
  16. Recurrence Equation for Divide and Conquer
  17. Finding the Maximum and Minimum
  18. Merge Sort
  19. Quick Sort
  20. Stassen’s Matrix Multiplication
  21. Advantages and Disadvantages of Divide and Conquer
  22. Decrease and Conquer
    Insertion Sort
  23. Topological Sort
  24. Greedy Method
    General Method
  25. Coin Change Problem
  26. Knapsack Problem
  27. Job Sequencing with Deadlines
  28. Minimum Cost Spanning Trees
    2 Topics
  29. Single Source Shortest Paths
    1 Topic
  30. Optimal Tree Problem
    1 Topic
  31. Transform and Conquer Approach
    1 Topic
  32. Dynamic Programming
    General Method with Examples
  33. Multistage Graphs
  34. Transitive Closure
    1 Topic
  35. All Pairs Shortest Paths
    6 Topics
  36. Backtracking
    General Method
  37. N-Queens Problem
  38. Sum of Subsets problem
  39. Graph Coloring
  40. Hamiltonian Cycles
  41. Branch and Bound
    2 Topics
  42. 0/1 Knapsack problem
    2 Topics
  43. NP-Complete and NP-Hard Problems
    1 Topic
Lesson 6, Topic 2
In Progress

Bubble Sort

Lesson Progress
0% Complete

Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if they are not in the intended order. The order can be ascending or descending.


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. 
KodNest Bubble sort 0 1

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.

KodNest 2
KodNest Bubble sort 2 1
KodNest 4

Bubble Sort Algorithm

bubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort

Bubble Sort Program in C

// Bubble sort in C
    #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);
    }

Optimized Bubble Sort

In the above code, all possible comparisons are made even if the array is already sorted. It increases the execution time.

The code can be optimized by introducing an extra variable swapped. After each iteration, if there is no swapping taking place then, there is no need for performing further loops.

In such case, variable swapped is set false. Thus, we can prevent further iterations.

Algorithm for optimized bubble sort is

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort

Optimized Bubble Sort Program

// Optimized bubble sort in C
#include <stdio.h>
void bubbleSort(int arrayay[], int size)
{
  for (int step = 0; step & lt; size - 1; ++step)
  {
    // The variable "swapped" is introduced for optimization.
    int swapped = 0;
    for (int i = 0; i & lt; size - step - 1; ++i)
    {
      // To sort in descending order, change > to < in this line.
      if (arrayay[i] & gt; arrayay[i + 1])
      {
        int temp = arrayay[i];
        arrayay[i] = arrayay[i + 1];
        arrayay[i + 1] = temp;
        swapped = 1;
      }
    }
    // If there is not swapping in the last swap, then the array is already sorted.
    if (swapped == 0)
      break;
  }
}
void printarrayay(int arrayay[], int size)
{
  for (int i = 0; i & lt; size; ++i)
  {
    printf("%d  ", arrayay[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");
  printarrayay(data, size);
}

Complexity

Bubble Sort is one of the simplest sorting algorithms. Two loops are implemented in the algorithm.

CycleNumber of Comparisons
1st(n-1)
2nd(n-2)
3rd(n-3)
…….……
last1

Number of comparisons:(n-1) + (n-2) + (n-3) +.....+ 1 = n(n-1)/2 nearly equals to n2

Complexity: O(n2)

Also, we can analyze the complexity by simply observing the number of loops. There are 2 loops so the complexity is n*n = n2

Time Complexities:

  • Worst Case Complexity: O(n2)

    If we want to sort in ascending order and the array is in descending order then, the worst case occurs.
     
  • Best Case Complexity: O(n)

    If the array is already sorted, then there is no need for sorting.
     
  • Average Case Complexity: O(n2)

    It occurs when the elements of the array are in jumbled order (neither ascending nor descending).

Space Complexity:

Space complexity is O(1) because an extra variable temp is used for swapping.

In the optimized algorithm, the variable swapped adds to the space complexity thus, making it O(2).


Bubble Sort Applications

Bubble sort is used in the following cases where

  1. the complexity of the code does not matter.
  2. a short code is preferred.
KodNest Training New Batch is starting on 02nd November 2020. Attend one week free demo classes.Register Now

New Report

Close