The 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. The algorithm will go through several passes through the data to examine of there are no swaps are needed. One thing to note with the bubble sort is not suited for data with large elements.

Breaking it down step by step

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