Bubble Sort
Bubble Sort
• After pass 2 : 2, 1, 4, 6, 8
2 1 4 6 8
• After pass 3 : 1, 2, 4, 6, 8
1 2 4 6 8 Sorted
Array
ALGORITHM FOR BUBBLE SORT
USING ARRAY
Assuming a list/array of n element.
1. Repeat step 2 and 3 for i = 0 to n-1.
2. Repeat following from j=0 to j < n – 2
• if arr [ j ] > arr [ j + 1 ], then swap places of these elements, else continue to the next iteration.
• Increment j by 1.
3. Increment i by 1.
4. Exit.
BUBBLE SORT PROGRAM IN C
BUBBLE SORT PROGRAM IN C
RABBITS AND TURTLES
• The positions of the elements in bubble sort will play a large part in determining its
performance. Large elements at the top of the list do not pose a problem, as they are
quickly swapped downwards. Small elements at the bottom, however, as mentioned
earlier, move to the top extremely slowly.
• Higher value elements, or element that occur at the end of the sequence, take few passes
and switches to get to the right spots. These are called “rabbits”.
• Lower value elements at last positions move very slowly to their correct places. These
are called :turtles”.
ADVANTAGES OF THE BUBBLE
SORT
• The bubble sort is a very memory-efficient because all of the ordering occurs within the
array or list itself. No new memory is allocated
• No new data structures are necessary, for the same reason.
• The bubble sort is comprised of relatively few line of code.
DISADVANTAGES OF THE BUBBLE
SORT
• The main disadvantage of the bubble sort method is the time it require.
• Presence of turtles can severely slow the sort.
THANK YOU!