Page 58 - Touchcode_C8_Flipbook
P. 58
Example 1:
In your physical education classes or sports classes, you lined up in a random order
in front of the teacher. Teacher will arrange you according to your height in ascending
order. The bubble sort algorithm comes in handy here. In this case, every student’s
height is an element of the list. With every pass the teacher goes over the students, and
start standing student in a more orderly fashion till all of them stand according to height.
1 Pass 2 Pass Sorted according to height
nd
st
Example 2: Consider a set of numbers 2, 6, 5, 4, 3; that needs to be sorted in ascending
order using bubble sort.
Concept: If the number on the left is greater than the number on the right, swap the two
numbers until the numbers are sorted in ascending order.
1. List of numbers, to be sorted in ascending order:
2 6 5 4 3
2. Compare the first two numbers (2 and 6) and find out which one is greater.
3. Since 6 is already greater than 2, no change is made.
2 6 5 4 3
4. Compare the numbers 6 and 5; Since 6 is greater than 5, we will swap these two numbers.
2 5 6 4 3
5. Next, we compare 6 and 4; Since 6 is greater than 4, we will swap these two numbers.
2 5 4 6 3
6. Lastly, we compare 6 and 3; Since 6 is greater than 3, we will swap these two numbers.
2 5 4 3 6
56 Touchcode-VIII

