Bubble Sort in JavaScript

  1. The algorithm will compare two adjacent elements. For example a and b.
  2. The algorithm will swap them if they are out of order by checking whether a is less than b
  3. The algorithm will repeat steps 1. and 2. until the end of the array is reached. At the end of the iteration, the largest number should be at the very end of the array.
  4. The algorithm will then ignore the last item and repeat step 1 until all the elements are sorted

Implementation

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]);

Optimize it!

There is one specific scenario in which we can optimize the algorithm a bit.

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 the current element to every other element in the array.

Conclusion

That’s it! Bubble sort isn’t a very demanding algorithm to learn. I’ll post more sorting algorithms in the future. In the meantime, please check my LinkedIn for any questions. Happy Coding!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store