Toy problem: BubbleSort

Fakhreddine Messaoudi
2 min readMar 6, 2021

Hack Reactor

Hello guys, today I’m going to explain the bubble sort algorithm and explain it as simply as I can.

Let’s get started

The first thing, there is a lot of other algorithms that sort arrays with different way. In this toy problem, we have the most basic sorting algorithm also it's easy to understand.
First of all, let’s take this example [5,6,2,3]:

The first thing you need to know is, we will be checking and comparing every two elements and then switch them. Let me make this clear:

[5,6,2,3][5,6,3,2][5,3,2,6][5,3,2,6][3,2,5,6][2,3,5,6]

This is how exactly the bubble sort works. So, let’s jump into the code.


// we need to create a function that it swap 2 elements
const switching = (x, y, array) => {
let currentValue = array[x];
array[x] = array[y];
array[y] = currentValue;
return array;
}
// we need to set our stop condition and set it to true
let swap = true;

Step one

we need to use while loop and check our condition if it's true we will loop else we will return the array, which means the array is already sorted

Step two

--

--

Fakhreddine Messaoudi

Was man shreibt, bleibt. Support my writing with a simple follow and clapp!