Member-only story
The bubble sort is an algorithm that compares two adjacent elements and swaps them until they are sorted in the intended order.
Because the bubble sort is a very common algorithm, it is highly likely that an applicant for a Python developer role will be asked to code it.
The psuedocode for the bubble sort is:-
- Define the function, bubble_sort, which takes an unsorted array as its input.
- Within the function, define the variable, n, as the length of the unsorted array.
- Within the function, define the variable, swapped, and initialise it to the boolean value as False.
- Within the function, create a food loop, with i as the iterator, that will iterate through the length of n-1.
- Within the for loop, create another for loop, with j as the iterator, that will iterate through the length of n-i-1.
- Within the for loop with j as the iterator, if the j element of the array is greater than the j+1 element of the array then set the variable swapped to True and swap out the element j of the array with j+1 of the array.
- Within the for loop with j as the iterator, if the elements are not swapped then the function will end and the sorted array will be returned.
The code in Python for the bubble_sort algorithm can be found below:-