Bubble Sort

Today we will take a look on some sorting algorithms written in javascript.

Sorting is so important and potentially so timeconsuming,it has been the subject of extensive research in
computer science, and some very sophisticated methods have been developed.

Some sorting algorithms are the merge sort, the instertion sort, binary search tree etc. The difference between all of these algorithms is the efficiency and the speed,
because as anyone can understand, some algorithms are faster than other.

Let's take a look to a very simple algorithm the bubble sort.

if you want to visualize this algorithm first you can do that by clicking this link https://visualgo.net/en/sorting

What this algorithm do

Imagine that you have an array with numbers :

var array = [1,4,2,6,9,3];

and we want to sort these numbers in a way that the n-1 to be always less than n. So the output we want to be [1,2,3,4,6,9]

So the bubble sort algorithm is working like this. You start at the left end of the line and compare the two numbers in positions 0 and 1. If the one on the left (in 0) is bigger, you
swap them. If the one on the right is bigger, you don’t do anything. Then you move over one position and compare the numbersin positions 1 and 2. Again, if the one on
the left is bigger, you swap them. And so on.

The code


function bubbleSortBasic(array) {
for(var i = 0; i < array.length; i++) {
for(var j = 1; j < array.length; j++) { if(array[j - 1] > array[j]) {

var temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
return array;
}

Summary and Time complexity

Hence the time complexity of Bubble Sort is O(n2). The main advantage of Bubble Sort is the simplicity of the algorithm.
The space complexity for Bubble Sort is O(1), because only a single additional memory space is required i.e. for temp variable.

Also, the best case time complexity will be O(n), it is when the list is already sorted.

Σχόλια