The bubble sort algorithm is a simple sorting algorithm where each pair of numbers are compared and the elements are swapped if they are not in order of smallest to largest. Likewise, the algorithm will go through several passes through the data to examine if there are no swaps are needed. However, one thing to note with the bubble sort is that it is not suited for data with large elements.

Breaking down bubble sort algorithm step by step

The sorting array of numbers “5 1 4 2 8” from lowest to highest using a bubble sort.

bubble sort diagram

Code Implementation


#include <iostream>

using namespace std;

int main()
{
int hold;
int bubble[10];

cout << "Please enter in 10 Numbers\n";

for(int i = 0; i < 10; i++)
{
cin >> bubble[i];
}

cout << "\n";
cout << "\nOriginal values entered: \n";

for(int j = 0; j < 10; j++)
{
cout << bubble[j];
cout << "\n";
}
// Bubble sorting code works here
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
// Sort from smallest to largest
if(bubble[j] > bubble[j+1])
{

// Swap elements
hold = bubble[j];
bubble[j] = bubble[j+1];
bubble[j+1] = hold;
}
}
}

cout << "\nSorted array is\n";
for(int i = 0; i < 10; i++)
{
cout << bubble[i] << "\n";
}
}

Share this post

FAQ's

What is meant by bubble sort algorithm?

The bubble sort algorithm is a simple sorting algorithm where each pair of numbers are compared and the elements are swapped if they are not in order of smallest to largest.

What is the algorithm for bubble sort?

The algorithm for the bubble sort is that it will go through several passes through the data to examine if there are no swaps needed.

What is pseudocode for bubble sort?

  1. Compares first two elements
  2. Swaps elements if required
  3. Repeats until all the elements in the array are sorted