Write Bubble Sort Algorithm in Javascript

Norfa Bagas
2 min readApr 16, 2022

--

There are many sorting algorithms out there, and one of the simplest sorting algorithms is Bubble Sort. This algorithm works by swapping two adjacent values, and this process is repeated until all values are in the right order.

For example, we have an array of numbers
[1, 3, 8, 2]
And these are the steps to sort them by swapping adjacent values
-> [1, 3, 8, 2]
-> [1, 3, 2, 8] // first swap
-> [1, 2, 3, 8] // second swap
And we get the result: [1, 2, 3, 8]

And this is the implementation of Bubble Sort with Javascript

const bubbleSort = (arr) => {
const arrLength = arr.length;
for (let i = 0; i < arrLength; i++) {
for (let j = 0; j < arrLength - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j] + arr[j + 1];
arr[j + 1] = arr[j] - arr[j + 1];
arr[j] = arr[j] - arr[j + 1];
}
}
}
return arr;
}

In the above code, we loop over the array of values with index i. Then, for every index i, we loop over again with index j from 0 to i — 1. And we swap the value of position j with j+1 if the value is greater than j.

We can swap 2 values without using a temporary variable.
For example x = 2, y = 5
We can swap them like this:
x = x+y ~> x = 2+5=7
y = x-y ~> y = 7–5=2
x = x-y ~> x = 7–2=5

Copy the code and you can run it like this

-> bubbleSort([5, 1, 4, 0]) // call the function
-> [0, 1, 4, 5] // output

--

--

Norfa Bagas
Norfa Bagas

Written by Norfa Bagas

Software engineer. I also do some research related to Computer Vision and Artificial Intelligence

No responses yet