JavaScript Sorting Algorithms: Bubble Sort

Bubble sort is a procedure of sorting that begins with comparing the first and second items, then second and third and so on, until the end of the set is reached and repeat this process until all items are sorted correctly.

Image Source


12 6 8 4 9 1

In this array we have list of numbers where n = 6

The position of any number is i, and the number nearest to it is i+1, and the second nearest to it would i+2 and so forth.

We are going to be comparing the first and second, second and third, and so on.

i and i+1 value together, and if they are not in order we swap, we do this until we have list that requires no swap:

Just like I mentioned above we stop when we have not made any swaps at all.

Translating this to code – Pseudocode:


Explaining what this means:

First we are making a function called bubbleSort with arr as a parameter, then we are storing the parameter arr’s length into a variable called length.

We are making a variable called temp which we will use later.

Let us use an example to illustrate what is going on.

The first for loop with i, will iterate through the array length starting from 0, whereas the for loop within j will only loop within the constraint of length – i – 1.


We have an array that contains 6 numbers [8,4,6,7,3,1]

i = 0,

j goes from 0 – 5 ( = 6 – 0 – 1 (hence length – i – 1) )

We have a condition that says if arr[j] > arr [j+1]. This means if the value on the left is greater than the value on the right.

temp = arr[j];

we are using the temp to assign it the value on the left.

arr[j] = arr[j+1];

arr[j+1] = temp;

we are reassigning arr[j] with the value on the right, and reassigning arr[j+1] with the value in temp.

That concludes bubble sort.

Related Posts