Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bubble sort and comparison of elementary methods.

Similar presentations


Presentation on theme: "Bubble sort and comparison of elementary methods."— Presentation transcript:

1 Bubble sort and comparison of elementary methods

2 Bubble sort (1) An easy to understand and implement algorithm Keep passing through the input and exchange adjacent elements which are unsorted 1 st pass: the smallest item is put into position, 2 nd pass the 2 nd smallest etc

3 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); }

4 Bubble sort (3)

5 Bubble sort How many comparisons ? How many exchanges?

6 SelectInsertBubble Best/Worst /Avg BestWorstAvgAvg/ Worst Best Comp ~ N 2 /2N-1N 2 /2N 2 /4N 2 /2 Exch ~ N0N 2 /2N 2 /4N 2 /20 Comparison

7 (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

8 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

9 EMPIRICAL STUDY Insertion 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 itemsInteger keysString keys NSIBSIBSIB 1000148541005513012965170 20005433221436229569563295725 400021212987117579862314238913283210 S Selection sort I Insertion sort B Bubble sort


Download ppt "Bubble sort and comparison of elementary methods."

Similar presentations


Ads by Google