DEV Community

loading...
Cover image for JavaScript Bubble Sort

JavaScript Bubble Sort

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com ・2 min read

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;
}
Enter fullscreen mode Exit fullscreen mode

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 ]
Enter fullscreen mode Exit fullscreen mode

Bubble sort can be optimized in a number of different ways. For example, if there were no exchanges, then the array is already sorted and we can stop the execution.

Another alternative is Cocktail Sort, which first pushes up the biggest element and then moves down the smallest one.

Learn Full Stack JavaScript

Discussion (0)

pic
Editor guide