DEV Community

Cover image for Bubble Sort: A JavaScript Implementation Guide
Tochi
Tochi Subscriber

Posted on

Bubble Sort: A JavaScript Implementation Guide

Imagine a puzzle game where you have six holes. Each hole holds a colored ball (red, blue or green). To win that round in the game, you have to sort the balls so that all the red ones come first, then the green ones, and finally the blue ones. But you can only compare two balls that are side by side, and if they’re not in the right order, you swap them.

You go through the row of balls, checking two at a time. If they’re in the wrong order, you swap them. As you repeat this process, the balls slowly move into the right positions (red moves forward, blue shifts to the back). You continue until no more swaps are needed. That is how the bubble sort algorithm works. So, what is bubble sort?

What is Bubble Sort?

Bubble sort is a type of sorting algorithm that goes through a list of items and arranges the items on the list in the right order. It does this by comparing two items that are side by side and swapping them if they are in the wrong order.

How does it work?

Let’s say you have an unsorted array of numbers: const array = [10, 7, 6, 1]. Your task is to sort this array in ascending order. Naturally, your first thought might be, "Oh, that's easy. Just use the JavaScript built-in sort method." And you'll be correct to think that. But what if, like me, you were in an interview and your interviewer asked you to sort the array without any built-in method? How would you go about it?

  • Start at the beginning of the array and move through it one item at a time.
  • Compare each item with the one next to it.
  • Swap the items if the current item is greater than the next one.
  • Repeat this process for the entire array.
  • Continue looping through the array until no more swaps are needed and your array is fully sorted.

Let's code!

const sortArray = (numList) => { for (let j = 0; j < numList.length; j++) { for (let i = 0; i < numList.length; i++) { if (numList[i] > numList[i + 1]) { let temp = numList[i]; numList[i] = numList[i + 1]; numList[i + 1] = temp; } } } return numList; }; // console.log("sorted===>", sortArray(arr)); 
Enter fullscreen mode Exit fullscreen mode

Explanation.

  • const sortArray = (numList) => { ... } defines a function called sortArray that takes an array of numbers (numList) and returns a sorted version of it.
  • for (let j = 0; j < numList.length; j++) is the outer loop. It runs the same number of times as the length of the list. It loops through the entire list from start to finish.
  • for (let i = 0; i < numList.length; i++) is the inner loop. This is the loop that does the actual comparison. It compares the current item with the item next to it.
  • if (numList[i] > numList[i + 1]) is a conditional statement that checks if the current number is bigger than the one next to it. If the condition is true, then we need to swap them so the bigger number moves to the right.
  • let temp = numList[i]; If the conditional statement is true, then this runs. This temporarily stores the current number in a variable called temp. We are storing in a variable because we're about to change numList[i], and we still need its value to complete the swap.
  • numList[i] = numList[i + 1]; moves the next number to the current spot, and this, numList[i + 1] = temp; puts the original number (from temp) into the next spot.
  • return numList; returns the sorted array once all the sorting is done.
  • console.log("sorted===>", sortArray(arr)); prints out the sorted array in the console so we can see the result.

Why Do We Use Two Loops in Bubble Sort?

The inner loop goes through the list once and compares each number with the next one. If the number is bigger than the one next to it, it swaps them. So if it loops just once, we'll get: [7,10,6,1] → [7,6,10,1] → [7,6,1,10] → [7,6,1,10]. This is why the outer loop is needed. The outer loop tells your code: “Go through the list again... and again...” until everything is sorted. It does this n-1 times, where n is the length of the array.

Here is a step-by-step breakdown of what happens.

  • 1st time (outer loop index = 0): The inner loop runs and pushes the biggest number (10) to the end. The result is [7,10,6,1] → [7,6,10,1] → [7,6,1,10] → [7,6,1,10]. After this round, 10 is in the correct place.
  • 2nd time (outer loop index = 1): Now the second-biggest number (7) gets pushed toward its correct place. [7,6,1,10] → [6,7,1,10] → [6,1,7,10] → [6,1,7,10].
  • 3rd time (outer loop index = 2): The smallest numbers (6 and 1) are still in the wrong spots. This time, they get moved into place. [6,1,7,10] → [1,6,7,10] → [1,6,7,10] → [1,6,7,10].
  • 4th time (outer loop index = 3): Now everything is sorted. Even though nothing changes, the loop still runs just to check.

So why do we need the outer loop? Because just looping once is not enough. You need to keep looping until all numbers are in the right place. Without the outer loop, only the largest number will be in place. The rest will still be scrambled.

Conclusion.

Bubble sort is one of the simplest JavaScript sorting algorithms to understand and use. However, bubble sort is not the fastest option, especially for large lists. It has a time complexity of O(n^2), which means it has a quadratic time complexity. This means the time it takes to finish grows quickly as the list gets longer. It also has a space complexity of O(1), which means it has a constant space complexity. It means it doesn’t need any extra memory to do the sorting. So while bubble sort is great for learning how sorting works, it’s also not the best choice for real-world applications where performance matters.

Top comments (0)