# JavaScript Algorithms: Bubble Sort

Bubble sort is a simple algorithm for sorting, but it's also quite inefficient, as its worst case is `O(n^2)` complexity.

But it's worth learning about it.

We loop through an array, and we keep comparing one item to the one right next to it.

If the item on the right is smaller, we swap the two positions.

Here's our implementation:

``````const bubbleSort = (originalArray) => {
let swapped = false

const a = [...originalArray]

for (let i = 1; i < a.length - 1; i++) {
swapped = false

for (let j = 0; j < a.length - i; j++) {
if (a[j + 1] < a[j]) {
;[a[j], a[j + 1]] = [a[j + 1], a[j]]
swapped = true
}
}

if (!swapped) {
return a
}
}

return a
}
``````

You can see the `O(n^2)` comes from the fact we are looping the array 2 times, to check if we need to swap the item with the one on the right.

We start with the first element, and we compare it with the second. If the first is bigger, we swap them. Otherwise we leave it as-is, and we switch to the second element of the array. We compare it with the third. Again, if the 2nd is bigger than the 3rd, we swap them, and we continue swapping until it finds its position in the array.

Here's an example:

Suppose we run `bubbleSort([2, 1, 3])`.

First we compare 2 with 1. 2 is > 1, so we swap them:

``````1 2 3
``````

then we compare 2 with 3. 2 < 3, so we leave it as-is. We skip the last element, since we know that due to our workflow, it's always going to be the biggest element.

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

• Learn to code in THE VALLEY OF CODE, your your web development manual
• Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
• I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
• Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
• Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
• Find me on X