# Js Bubble Sort

## Javascript Bubble sort implementation#

In this post we will implement bubble sort using js. In bubble sort we compares each value with next value and then we swaps the values of those two value.

This requires two loops which have complexity of `O(n^2)`. we can compute the operations executing in loops by simple variable.

like below example of basic bubble sort.

``````var arr = [2, 3, 4, 2, 6, 12, 5, 20, 31, 9];

for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {

if (arr[i] > arr[j]) {
// swap values
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

}
}
}
console.log(arr);

``````

this will sort the arr variable but look at the number of opration it is doing. create new variable

``````var ops = 0 ;
``````

and increment this variable in inner loop which is second loop

``````var arr = [2, 3, 4, 2, 6, 12, 5, 20, 31, 9];
var ops = 0;
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
ops++;
if (arr[i] > arr[j]) {
// swap values
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

}
}
}
console.log("Operations => ", ops)
console.log(arr);
``````

if you will print the ops and result it will be like

``````Operations =>  100
[
31, 20, 12, 9, 6,
5,  4,  3, 2, 2
]
``````

To run this programme nodejs must be installed and run it with below command

``````node filename.js
``````

it is doing 100 operation because there is 10 element in the array. it is doing 10x10=100 operations, we can further reduce this complexity.

now change the second loop initialization like below

``````for (var j = i + 1; j < arr.length; j++) {

}
``````

now run and see the output it will print like below

``````Operations =>  45
[
2, 2,  3,  4,  5,
6, 9, 12, 20, 31
]
``````

Now it is doing only 45 operations, our data is sorted but in reverse order. if you want to change from ascending to descending order and vice versa just change the if condition with less than to greater than. As you can see we have save around 55 operation just by little changing the logic.