9
Bubble sort and comparison of elementary methods

Bubble sort and comparison of elementary methods

Embed Size (px)

Citation preview

Page 1: Bubble sort and comparison of elementary methods

Bubble sort and comparison of elementary methods

Page 2: Bubble sort and comparison of elementary methods

Bubble sort (1)

• An easy to understand and implement algorithm

• Keep passing through the input and exchange adjacent elements which are unsorted

• 1st pass: the smallest item is put into position, 2nd pass the 2nd smallest etc

Page 3: Bubble sort and comparison of elementary methods

Bubble sort (2)

static void bubble(ITEM[] a, int l, int r) { for (int i = l; i < r; i++) for (int j = r; j > i; j--) compExch(a, j-1, j);

}

Page 4: Bubble sort and comparison of elementary methods

Bubble sort (3)

Page 5: Bubble sort and comparison of elementary methods

Bubble sort

• How many comparisons ?

• How many exchanges?

Page 6: Bubble sort and comparison of elementary methods

Select Insert Bubble

Best/Worst

/Avg

Best Worst Avg Avg/Worst

Best

Comp

~

N2/2 N-1 N2/2 N2/4 N2/2 N2/2

Exch

~

N 0 N2/2 N2/4 N2/2 0

Comparison

Page 7: Bubble sort and comparison of elementary methods

Comparison

• (X,Y) : actual, current position

• Insertion sort does not look ahead of its current position

• Select sort does not look back

Hor axis: final position

Vert axis: current position

insert select bubble

Page 8: Bubble sort and comparison of elementary methods

Comparison

• Sort according to angle– Dark lines: accessed

in each pass– Gray: no touched

• Insert: item goes halfway back

• Select/Bubble sort: entire set to find minimum

insert select bubble

Page 9: Bubble sort and comparison of elementary methods

EMPIRICAL STUDYInsertion sort and selection sort are about twice as fast as bubble sort for small files,

Running times grow quadratically (when the file size grows by a factor of 2, the running time grows by a factor of 4). None of the methods are useful for large randomly ordered files.

When comparisons are expensive— for example, when the keys are objects or strings—then insertion sort is much faster than the other two because it uses many fewer comparisons.

Not included here is the case where exchanges are expensive; then selection sort is best.

int items Integer keys String keys

N S I B S I B S I B

1000 14 8 54 100 55 130 129 65 170

2000 54 33 221 436 229 569 563 295 725

4000 212 129 871 1757 986 2314 2389 1328 3210

S Selection sort I Insertion sort B Bubble sort