Code to implement bubble sort - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals and sorts it using bubble sort. In Bubble Sort, each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Example

Let’s write the code for this function −

const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45];
const swap = (items, firstIndex, secondIndex) => {
   var temp = items[firstIndex];
   items[firstIndex] = items[secondIndex];
   items[secondIndex] = temp;
};
const bubbleSort = items => {
   var len = items.length,
   i, j;
   for (i=len-1; i >= 0; i--){
      for (j=len-i; j >= 0; j--){
         if (items[j] < items[j-1]){
            swap(items, j, j-1);
         }
      }
   }
   return items;
};
console.log(bubbleSort(arr));

Output

The output in the console: −

[
   2,  4, 4,  4,  7,
   8,  8, 8, 23, 23,
   45, 56
]
raja
Published on 15-Sep-2020 09:25:25
Advertisements