Bubble Sort

Sort Type: Comparison-Based Sorting / Transposition Sorting


Algorithm

Description:

Like all comparison based sorting techniques Bubble Sort is based on comparing two keys and rearranging the associated data in order to place the keys in ascending or descending order.

Bubble Sort was one of the first sorting methods created. It is also the simplest. Bubble Sort was so named because as you repeatedly scan the array of records making comparisons the lower value keys gradually "bubble" to the start of the array.


Data holder: A filled array of data structures.

Technique:
  1. Start from the beginning of the array and compare each pair of sequential records.
  2. If the key for record i is greater than the key for record i+1 then swap them.
  3. Repeat this procedure, decreasing the number of comparisons by 1 each time until the number of comparisions to be made is 0.


Analysis: In the worst case Bubble Sort runs in O(n2) time, but a detailed analysis will also show that in all cases it is the worst performer of all the sorts which run in O(n2) time in the worst case, i.e. structures already sorted but in reverse order.

Sample Code:

/***************************************/
/* BubbleSort()                        */
/*                                     */
/* Sort records on integer key using   */
/*  a bubble sort.                     */
/***************************************/
void BubbleSort(StructType DataArray[], int count)
{
    int         i, j;
    StructType  temp;

    for(i=0; i<count; i++)
    {
        for(j=0; j<(count-i - 1); j++)
        {
            if(DataArray[j].key > DataArray[j+1].key)
             {
                 temp = DataArray[j];
                 DataArray[j] = DataArray[j+1];
                 DataArray[j+1] = temp;
             }

        }
    }
}