Understanding bubble sort algorithm
The strategy from the earlier example could be used to create an algorithm. To explain this algorithm, we will take an array as an input list, but the same algorithm can be applied to any list data structure.
Algorithm
The bubble sort algorithm conceptually divides the array into two parts: an unsorted subarray and a sorted subarray. Initially, all elements belong to the unsorted portion, while the sorted portion is empty.
Unsorted and sorted subarrays
In each pass, the algorithm repeatedly compares adjacent elements in the unsorted section and swaps them if they are out of order.
Swap if the elements are out of order
As these comparisons continue from left to right, the largest value "bubbles up" to the end of the unsorted portion.
Keep swapping adjacent elements if they are out of order
Liking the course? Check our discounted plans to continue learning.