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!

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

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Building a BigCommerce App Using Laravel and React

How we created a go-to destination for the “Cricket World Cup”- the most celebrated event in India!

l understand please coinbase subscribe

Clean Approach to React + Bootstrap

Get Hooked on React Hooks!

8 Concepts to Make You Code Truly Pure Functions in JavaScript

What is JWT (Json web token)

React Native : The Positive’s & Negative’s 🔥

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
Marcus Siegel

Marcus Siegel

More from Medium

Async Await in JavaScript

Moving with the “Flow” via React

Implementing a Stack in Vanilla Javascript

Getting started with Javascript