Bubble sort

How to swap 2 values ?

 

How we can swap 2 values , a[i] and a[i+1] ? let say that a[i] contain 4 and a[i+1] contain 9 . Can we use the following code?

a[i]=a[i+1];

a[i+1]=a[i];

 

After executing the first line a[i]=a[i+1]; a[i] =9 and a[i+1] also contain 9 , where the 4 went ? You know now that you replaced it with 9 . Then what should we do ? We need an extra variable to hold (store) the value of 4, and the new code will be :

 

hold=a[i];          // store the value of 4

a[i]=a[i+1];        // a[i] and a[i+1] equals to 9 

a[i+1]=hold;      //a[i+1] equals to 4

 

Sorting Program

 

#include <stdio.h>
#define SIZE 10

int main()
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i, pass, hold;

printf( "Data items in original order\n" );

for ( i = 0; i <= SIZE - 1; i++ )
printf( "%4d", a[ i ] );

for ( pass = 0; pass < SIZE - 1; pass++ ) /* passes */
   for ( i = 0; i < SIZE - 1; i++ )                 /* one pass */
        if ( a[ i ] > a[ i + 1 ] )             /* one comparison */
           {
             hold = a[ i ]; /* one swap */
             a[ i ] = a[ i + 1 ];
             a[ i + 1 ] = hold;
           }


printf( "\nData items in ascending order\n" );

for ( i = 0; i <= SIZE - 1; i++ )
printf( "%4d", a[ i ] );

printf( "\n" );

return 0;
}

 

Descent sort Example


The table below shows a list of numbers before, during, and after a bubble sort for descending order. Several passes have to be made through the array before it is finally sorted. The bubble sort is easy to program, but it is slower when compared to many other sorting algorithms.

 

Array at beginning: 

54

39

76

56

90

46

After Pass #1:

54

76

56

90

46

39

After Pass #2: 

76

56

90

54

46

39

After Pass #3: 

76

90

56

54

46

39

After Pass #4: 

90

76

56

54

46

39

Array at end of sort: 

90

76

56

54

46

39