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;

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

We need to set our condition to false to do not fall in an infinity loop and we will iterate over the array, then we need to check per two elements if the first element is bigger than the second we will change back our state to true and then invoke the switching function that we created already inside it.

So, let me make this clear by these lines of code.

let swap = true;
while (swap) {
swap = false;
for (let i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
swap = true;
console.log("==>", i, i + 1, "<==");
switching(i + 1, i, array);
}
}
}
return array;
};

We will end up having a result that looks like this:

Go and try it!!👐🏻
I will catch you up in the next “Toy Problem”

If you want master something teach it.