Bubble sort algorithms
The idea behind the bubble sort algorithm is very simple. Given an unordered list, we compare adjacent elements in the list, and after each comparison, we place them in the right order according to their values. So, we swap the adjacent items if they are not in the correct order. This process is repeated n-1
times for a list of n
items.
In each iteration, the largest element of the list is moved to the end of the list. After the second iteration, the second largest element will be placed at the second-to-last position in the list. The same process is repeated until the list is sorted.
Let’s take a list with only two elements, {5
, 2
}, to understand the concept of bubble sort, as shown in Figure 11.1:
Figure 11.1: Example of bubble sort
To sort this list of two elements, first, we compare 5
and 2
; since 5
is greater than 2
, it means they are not in the correct order, so we swap these values to put them in the correct order. To swap...