JavaScript Functions - Bubble Sort algorithm

Subscribe to my newsletter and never miss my upcoming articles

NOTE: in this article I used bubble sort to provide more function examples.

Bubble Sort Algorithm

Bubble Sort is a sorting algorithm, which is commonly used in computer science. Bubble Sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.

Steps on how it works

Unsorted array: [40, 20, 30, 10, 60, 15, 0, 1]

Always sorted in Ascending order. (swap)

  1. Start with the first two elements and sort them in ascending order. we compare the element to the adjacent elements to check which one is greater, and swap.
  2. Compare the second and third element to check which one is greater, and swap
  3. Compare the third and fourth element to check which one is greater, and swap
  4. Compare the fourth and fifth element to check which one is greater, and swap
  5. Compare the fifth and sixth element to check which one is greater, and swap
  6. Compare the sixth and seventh element to check which one is greater, and swap
  7. Compare the seventh and eight element to check which one is greater, and swap

Repeat steps 1–7 until no more swaps are required.

Please see below for code and example of the output:

Thanks for reading this article.

Let's Connect

Next article will be: Selection Sort Algorithm

No Comments Yet