JavaScript Sorting Algorithms: Bubble Sort
Tags: algorithms, javascript, sort
Published: 2020-12-27 21:34:16

> You can read more posts on programming and tech on my [blog](https://thedukh.com/). This series will be updated as soon as I catch some free time :)


# Introduction
So I have this thing on my blog called the JavaScript Sorting Algorithm series. This series of posts will try to explain and implement different sorting algorithms in our favorite scripting language - JS of course! And we will start our journey with the easiest one - <em>bubble sort</em>.


Although the <em>bubble sort</em> algorithm compared to other sorting algorithms isn't that efficient, and isn't used anywhere in the real world, interviewers still commonly check for it during interviews. It is good to at least know how it works under the hood.


How does <em>bubble sort</em> (you can also find it under the alternate name <em>sinking sort</em>) work. The algorithm 'bubbles' large values (thus the name) to the top on each iteration of the algorithm. Then it compares adjacent elements between each other and swaps them if they are in the wrong order.


<p>Pseudo code looks like this:</p>


<!-- wp:list {"ordered":true} -->
<ol><li>The algorithm will compare two adjacent elements. For example a and b.</li><li>The algorithm will swap them if they are out of order by checking whether <em>a</em> is less than <em>b</em></li><li>The algorithm will repeat steps 1. and 2. until the end of the array is reached. At the end of iteration the largest number should be at the very end of the array.</li><li>The algorithm will then ignore the last item and repeat step 1, until all the elements are sorted</li></ol>
<!-- /wp:list -->


Let us visualize this algorithm using the inputs <em><span style="color:blue">`[15, 6, 4, 18, 7, 13, 1]`</span></em>.
The algorithm is vizualized using [visualgo](https://visualgo.net/en).
<br >

![Bubble Sort Vizualized](https://dev-to-uploads.s3.amazonaws.com/i/szzgmk9v7i9ef2fou0fe.gif)


So, at first we compare every element with its adjacent elements (green elements). If the element is larger - it will be swapped, during each iteration the largest element will be stuck to the end (orange elements). This process repeats itself until all the elements are sorted.

#Implementation
```javascript
function bubbleSort(arr) {
    for(let i = arr.length; i > 0; i--) {
        for(let j = 0; j < i - 1; j++) {
            if(arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
        }
    }

    return arr;
}

bubbleSort([15, 6, 4, 18, 7, 13, 1]);
```

Every iteration we reduce the iterator by 1 (because the last element is already sorted!). if the element is bigger than its adjacent element, we will use the swapping mechanism `[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]` (a pretty cool ES6 concept to swap items in place without the need for a temporary variable).

#Optimize it!
There is one specific scenario in which we can optimize the algorithm a bit.

If the array is almost sorted – needing to rearrange only an item or two, the algorithm still goes through all the loops, even though nothing is happening.

In order to fix this – we just need to check whether we made any swaps.

```javascript
function bubbleSort(arr) {
  let swapHappened;
  for (let i = arr.length; i > 0; i--) {
    swapHappened = true;
    for (let j = 0; j < i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapHappened = false;
      }
    }
    if (swapHappened) {
      break;
    }
  }
  return arr;
}
bubbleSort([2, 4, 6, 5, 7, 9, 12]);
```

#Big O Complexity
The average Big O of bubble sort is **O(n2)** because we iterate twice through the whole array. We need to compare current element to every other element in the array.

#Conclusion
That's it! Bubble sort isn't a very demanding algorithm to learn. We will post more sorting algorithms in the future. In the meantime, please check my [blog](https://thedukh.com/) for more tech articles.