Learn: Bubble Sort in Javascript

Riccardo Canella
Javascript by doing
3 min readJan 31, 2022

--

Bubble Sort is the simplest sorting algorithm that repeatedly scrolls through the list, compares adjacent elements and swaps them if they are in the wrong order. This sort is not used in real-world project because is very performs poorly.

Fast example

We start with an array, not sorted, composed like this: [8,5,2,6,12] The algorithm consists in cycling the array, checking if each element is ordered with respect to its next, and if necessary swap them, all this until by cycling the whole array 0 exchanges are obtained. In our example:

  1. Check if the first item is sorted with the next element (8,5)
  2. Swap the two value e pass to the next index (5,8)
  3. Check if the second element is sorted with the next element (8,2)
  4. Swap the two value e pass to the next index (2,8)
  5. Check if the third item is sorted with the next element (8,6)
  6. Swap the two value e pass to the next index (6,8)
  7. Check if the third item is sorted with the next element (8,12)
  8. In this case don’t swap the elements (8,12)

--

--

Riccardo Canella
Javascript by doing

Riccardo Canella @ricanella92 Love #basket, #bike and #HIMYM since my childhood. #Fullstack #Javascript addicted - https://canellariccardo.it