Bubble Sort Algorithm

The bubble sort gets its name because as array elements are sorted they gradually “bubble” to their proper positions,
like bubbles rising in a glass of soda.

A bubble sort will compare two adjacent element of an array and will swap them if they are out of order.
The compare starts with the first and second element. After that it will compare the second with the third element and so on. The process continues until the end of the list is reached.

bubble sort array

When the end of the array is reached, the bubble sort algorithm will returns to element one and starts the process all over again. So, when will the bubble sort algorithm stop? The bubble sort algorithm knows when it’s finish when there are no more “swaps”. This can be tracked by the bubble sort algorithm through a so called swap flag. (In our case the name of the flag is swap_flag.)

As you can see in the source below, the bubble sort algorithm is easy to program. But the bubble sort algorithm is slower than other sorting algorithms. Because the sort always needs a final extra pass to check to see that there are no more swaps are made. If there are no more swaps the swap flag is put up and the process ends.



#include<iostream>

using namespace std;
int main(void)
{
	int array[5];	// An array of integers.
	int length = 5;	// Lenght of the array.
	int i, j, swap_flag = 1; //swap_flag to 1 to begin initial pass.
	int temp;

	for (i = 0; i < 5; i++)
	{
		cout << "Enter a number: ";
		cin >> array[i];
	}

	for(i = 1; (i <= length) && swap_flag; i++)
	{
		swap_flag = 0;
		for (j=0; j < (length -1); j++)
		{
			if (array[j+1] > array[j])	// NOTE!
			{
				temp = array[j];	// swap elements
				array[j] = array[j+1];
				array[j+1] = temp;
				swap_flag = 1;	// A swap occurred.
			}
		}
	}
	for (i = 0; i < 5; i++)
	{
		cout << array[i] << endl;
	}
	return 0;
}

Note: To change the output in ascending order simply change > to <

That is all for this tutorial.

This entry was posted in Programming Algorithms. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There is currently one response to “Bubble Sort Algorithm”

Why not let us know what you think by adding your own comment!

  1. Pop the Bubbly « Value Hour on November 20th, 2012:

    […] Bubble Sort […]