8 elementary sorts-bubble

Post on 07-Aug-2015

81 views 0 download

Transcript of 8 elementary sorts-bubble

Bubble Sort Compares adjacent array elements

– Exchanges their values if they are out of order Smaller values bubble up to the top of the array

– Larger values sink to the bottom

Bubble Sort (cont.) Example:

512354277 101

0 1 2 3 4 5

Swap42 77

Bubble Sort (cont.) Example:

512357742 101Swap35 77

0 1 2 3 4 5

Bubble Sort (cont.) Example:

512773542 101Swap12 77

0 1 2 3 4 5

Bubble Sort (cont.) Example:

577123542 101

No need to swap

0 1 2 3 4 5

Bubble Sort (cont.) Example:

577123542 101 Swap5 101

0 1 2 3 4 5

Bubble Sort (cont.) Example:

77123542 5 101

Largest value correctly placed

0 1 2 3 4 5

Bubble Sort (cont.)

• Notice that only the largest value is correctly placed

• All other values are still out of order• So we need to repeat this process

77123542 5 101

Largest value correctly placed

0 1 2 3 4 5

Bubble Sort (cont.)

Repeat “Bubble Up” How Many Times? If we have N elements… And if each time we bubble an element, we place it in its correct location…

Then we repeat the “bubble up” process N – 1 times. This guarantees we’ll correctly place all N elements.

Bubble Sort (cont.)

77123542 5

0 1 2 3 4 5

101

5421235 77

0 1 2 3 4 5

101

42 5 3512 77

0 1 2 3 4 5

101

42 35 512 77

0 1 2 3 4 5

101

42 35 12 5 77

0 1 2 3 4 5

101

N -

1

Bubble Sort (cont.) What if the array was already sorted? What if only a few elements were out of place and after a couple of “bubble ups,”

the array was sorted? We want to be able to detect this and “stop early”!

Bubble Sort (cont.)

Using a Boolean “Flag” We can use a boolean variable to determine if any swapping occurred during the

“bubble up.” If no swapping occurred, then we know that the collection is already sorted! This boolean “flag” needs to be reset after each “bubble up.”

public static void BubbleSort( int [ ] num ){     int j;     boolean flag = true;   // set flag to true to begin first pass     int temp;   //holding variable

     while ( flag )     {            flag= false;    //set flag to false awaiting a possible swap            for( j=0;  j > num.length -1;  j++ )                               if ( num[ j ] > num[j+1] )   // change to > for ascending sort                   {                           temp = num[ j ];                //swap elements                           num[ j ] = num[ j+1 ];                           num[ j+1 ] = temp;                          flag = true;              //shows a swap occurred                    }             }       } } 

Bubble Sort (cont.) Excellent performance in some cases

– But very poor performance in others! Works best when array is nearly sorted to begin with Worst case number of comparisons: n2

Worst case number of exchanges: n2

Best case occurs when the array is already sorted:– n comparisons– 0 exchanges