Bubble Sort Using Javascript

vishal rana
3 min readNov 10, 2022

--

working of bubble sort

Bubble sort is a sorting algorithm that works with comparing the adjacent elements and swapping them if they are not in right order. Bubble sort has a very high time complexity. Bubble sort is not recommended for large data sets.

Time complexity: Bubble sort has a time complexity of O(n*n).

Let’s start with the sudo code of how it’ll generally works.

we need to keep in mind that with each iteration, we'll have largest element at the last of the array. so we can iterate  through n-i elements so that we don't cover once that are already sorted. checkout above GIF for its working. ☝️- Create a for loop(let say with variable i) to start from the end of the array and with need to run the loop until we reached second element from the array.- we need to create another loop(let say with variable j) that will start from the first element in the array and will run till the i.- Then we need to check if current element[j] is greater than the next element [j+1], if yes then we need to swap them.- At the end, we need to return the sorted array.

Let’s go through the code

const bubbleSort = (array) => {// Starting an initial loop from the last element and with each iteration eliminating the last elementfor (let i = array.length; i > 0; i--) {     // starting a loop to run from start till the end of upper loop   limit     for (let j = 0; j < i - 1; j++) {         // comparing if the value is greater than the next element         if (array[j] > array[j + 1]) {            // swapping the values.            [array[j], array[j + 1]] = [array[j + 1], array[j]];         }      }}// returning the sorted arrayreturn array;};

Explanation:

  • Line 8, we are initialising a for loop that will start from the last element and move toward the first element in the array and will decrement with each iteration. let’s suppose , we have an array [-2,5,1,6,4]. This loop will start from 4 and run till 5, as at the end of each iteration, we’ll have one sorted element at the last so we can skip that element in our next iteration. the array for next iteration will be [-2,1,5,4].
  • Line 10, we are starting a for loop that will run from the starting till the last unsorted index.
  • Line 12 to 15, we are comparing if the element are at right position, if not , we are swapping them.

The time complexity of the algorithm can be improved by checking if any swap happened inside the loop, if not, it means array is sorted.

Stay tuned for more to come, If you are new here, do checkout our Algorithms using Javascript blog, we are covering few of the most commonly used algorithms using javascript.

In the next blog, we’ll go through Insertion sort.

--

--

No responses yet