Before we start this activity let us first understand what bubble sort is:
Bubble sort is a method of sorting that works by repeatedly swapping adjacent elements if they are in incorrect order. In this problem, you need to sort a given set of numbers in ascending order using bubble sort.
Let us consider a set of numbers 1, 5, 4, 3, 2; that needs to be sorted in ascending order. If the number on the left is greater than the number on the right, it swaps the two numbers. This is done until the numbers are sorted in ascending order.
- Following is the list of numbers to be sorted in ascending order
- We compare the first two numbers and find out which one is greater.
- We start with 1 and 5. Since 5 is already greater than 1, no change is made
- Then we compare the numbers 5 and 4
- Since 5 is greater than 4, we will swap these two numbers.
- Next, we compare 5 and 3
- Since 5 is greater than 3, we will swap the two numbers.
- Lastly, we compare 5 and 2
- Since 5 is greater than 2, we will swap these two numbers
- The list of the numbers is rearranged as follows
- Notice 5 is the largest number in this list and arranged at the last position.
- We again start from the beginning and compare 1 with 4. Since 4 is greater than 1, no change is made.
- Then we compare the numbers 4 and 3
- Since 4 is greater than 3, we will swap these two numbers.
- Next, we compare 4 and 2
- Since 4 is greater than 2, we will swap the two numbers.
- Lastly, we compare 4 and 5. Since, 5 is greater than 4, no change is made.
- We again start from the beginning and compare 1 with 3. Since 3 is greater than 1, no change is made.
- Then we compare the numbers 3 and 2
- Since 3 is greater than 2, we will swap these two numbers.
- Next, we compare the numbers 3 and 4. Since 4 is greater than 3, no change is made.
- We again start from the beginning and compare 1 with 2. Since 2 is greater than 1, no change is made.
- The numbers are now all sorted in ascending order.
- The sorting is done until no more numbers need to be swapped.
- If we have 5 numbers, then the maximum time taken to sort the list will be 25 iterations.
Let us now write a python program to sort an array in MakeCode
Output for the code:
When you click on play the array will be sorted in ascending order.