Member-only story

Interview question: Code the bubble sort algorithm in Python

Crystal X
2 min readMay 31, 2023

--

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:-

  1. Define the function, bubble_sort, which takes an unsorted array as its input.
  2. Within the function, define the variable, n, as the length of the unsorted array.
  3. Within the function, define the variable, swapped, and initialise it to the boolean value as False.
  4. Within the function, create a food loop, with i as the iterator, that will iterate through the length of n-1.
  5. Within the for loop, create another for loop, with j as the iterator, that will iterate through the length of n-i-1.
  6. 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.
  7. 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:-

--

--

Crystal X
Crystal X

Written by Crystal X

I have over five decades experience in the world of work, being in fast food, the military, business, non-profits, and the healthcare sector.

No responses yet