80 likes | 457 Views
Bubble Sort Algorithm. Assuming you are “bubbling” from right to left:. Step 1 Compare the last two numbers on the extreme right. If the smaller number is on the right, swap the two numbers and reorder the list, if not, leave them. It is so named because numbers (or letters) which are in
E N D
Bubble Sort Algorithm Assuming you are “bubbling” from right to left: Step 1 Compare the last two numbers on the extreme right. If the smaller number is on the right, swap the two numbers and reorder the list, if not, leave them. It is so named because numbers (or letters) which are in the wrong place “bubble-up” to their correct positions (like fizzy lemonade) Step 2 Move one step back in the list (to the left) and compare the two numbers. If the smaller is on the right swap the two numbers and reorder the list, if not, leave them. You can “bubble” from bottom to top, right to left, top to bottom or left to right as long as you “bubble” in the same direction. Step 3 Repeat Step 2 until the two numbers on the extreme left have been compared, then return to Step 1. Step 4 Repeat Step 3 until all the numbers are in order (i.e. no more swaps are performed in a pass)
Sort the following numbers into ascending order: This is the result of the fourth pass - the 16 is now in the correct position – record this! This is the result of the first pass – the smallest number is now in the right position – record this! This is the result of the second pass - the 2 is now in the correct position – record this! This is the result of the third pass - the 15 is now in the correct position – record this! The final pass yields no change but you should still record this! 27 15 2 38 16 1 1 27 15 2 38 16 1 2 27 15 16 38 16 1 27 1 27 15 15 1 2 38 2 1 16 38 1 1 1 2 15 27 16 38 No swap 1 2 27 15 27 2 15 2 38 16 16 38 1 2 15 16 27 38 1 2 27 15 27 15 16 38 1 2 15 16 27 38 STOP No swap 1 2 15 16 27 27 16 38 1 2 15 16 27 38
Now try sorting this list: Bubble from right to left 25 36 17 9 41 37 57 11 9 25 36 17 11 41 37 57 9 11 25 36 17 37 41 57 9 11 17 25 36 37 41 57 9 11 17 25 36 37 41 57 STOP Bubble from left to right Now try sorting the list: 25 36 17 9 41 37 57 11 25 17 9 36 37 41 11 57 17 9 25 36 37 11 41 57 9 17 25 36 11 37 41 57 9 17 25 11 36 37 41 57 9 17 11 25 36 37 41 57 9 11 17 25 36 37 41 57 STOP 9 11 17 25 36 37 41 57