Bubble Sort Algorithm with C++ Code | Sorting Algorithms | Data Structures & Algorithms

In this tutorial we understand the working of bubble sort algorithm in data structures.

Bubble Sort –
  • Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
  • This algorithm is suitable for small data sets
  • Its average and worst case complexity are of (n^2) where n is the number of items.
  • It is known as bubble sort, because with every complete iteration the largest element bubbles up towards the last place or the highest index just like a water bubble rises up to the water surface.
Working –
  • Step 1 – Starting with the first element(index = 0), compare the current element with the next element of the array.
  • Step 2 – If the current element is greater than the next element of the array, swap them.
  • Step 3 – If the current element is less than the next element, move to the next element.
  • Step 4 – Repeat Step 1 till the list is sorted.
Bubble Sort Algorithm –
  1. declare variables – i, j
  2. loop : i = 0 to n – 1 // outer loop
    1. loop : j = 0 to n -i- 1 // inner loop
      1. if ( a[j]>a[j+1] ) then
        1. swap a[j] & a[j+1]
    2. end loop // inner loop
  3. end loop // outer loop
C++ Program to Implement BubbleSort –
#include < iostream >
  using namespace std;

void bubbleSort(int a[]) {
  for (int i = 0; i < 5; i++) {
    for (int j = 0; j < (5 - i - 1); j++) {
      if (a[j] > a[j + 1]) {
        int temp = a[j];
        a[j] = a[j + 1];
        a[j + 1] = temp;
      }
    }
  }
}

int main() {
  int myarray[5];
  int size;
  cout << "Enter 5 integers in any order: " << endl;
  for (int i = 0; i < 5; i++) {
    cin >> myarray[i];
  }
  cout << "Before Sorting" << endl;
  for (int i = 0; i < 5; i++) {
    cout << myarray[i] << " ";
  }

  bubbleSort(myarray); // sorting

  cout << endl << "After Sorting" << endl;
  for (int i = 0; i < 5; i++) {
    cout << myarray[i] << " ";
  }

  return 0;
}

YouTube video tutorials –

Leave a Reply

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