Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

The algorithm gets its name from the way smaller elements “bubble” to the top of the list while larger elements “sink” to the bottom.

Bubble sort has a worst-case and average complexity of О(n2), where n is the number of items being sorted. While there are faster sorting algorithms, bubble sort provides several advantages:

The algorithm is very simple to understand and implement. It can be easily adapted to sort lists of data with structure (such as records in a database). It performs well on small lists.

Despite these advantages, bubble sort is generally considered inefficient and is not used often in practice. When sorting large lists, other algorithms such as quicksort or heapsort are used instead.

Sorting is the process of arranging a sequence of objects in a particular order. You can sort any entities that can be compared.

Imagine an online store. You enter your query into the search bar and you get a list of results. To find the cheapest item, you need to sort the list in ascending order of price.

If you’re looking at your spending with a credit card and want to start with the largest, you need sorting too.

Under the hood of many computer programs, sorting is used to increase the efficiency of other algorithms, such as search.

Bubble Sort

One of the simplest sorting algorithms is bubble sort. In it, all objects are treated like air bubbles that float up to the surface of the water.

We compare adjacent elements of the array and swap them if the current element is greater than the next one.

When we reach the end of the array, the very last element is guaranteed to be in place. The biggest bubble has floated all the way up.

We repeat the whole process one more time, but this time up to the penultimate element.

After the second iteration, the last 2 elements will be in their positions. We will repeat the algorithm until we have only one element left in the array.

const bubbleSort = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i; j++) {
      if (arr[j] > arr[j + 1]) {
        let tmp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = tmp;
      }
    }
  }
  return arr;
}

For testing purposes, let’s create an array and call it testData. We print this array to the screen in the initial state, then sort it and eventually call console.log once more to verify the result.

const testData = [0, -1, 4, 5, 2, -3];

console.log(testData);  // [ 0, -1, 4, 5, 2, -3 ]
bubbleSort(testData);   // we call the sort function here
console.log(testData);  // [ -3, -1, 0, 2, 4, 5 ]

Read more JavaScript tutorials or Learn Full-Stack JS from scratch!