bubble sort in javascript

Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements and swaps them if they are in the wrong order. It has a worst-case and average complexity of O(n^2), where n is the number of items being sorted.

Here's how to implement bubble sort in javascript:

index.tsx
function bubbleSort(arr) {
   var len = arr.length;
   for (var i = 0; i < len; i++) {
       for(var j = 0; j < len - i - 1; j++) {
           if (arr[j] > arr[j + 1]) {
              var temp = arr[j];
              arr[j] = arr[j + 1];
              arr[j + 1] = temp;
           }
       }
   }
   return arr;
}
316 chars
14 lines

The bubbleSort() function takes an array as input and returns the same array with its elements sorted in ascending order. It uses a nested loop to compare adjacent elements and swap them if necessary. The outer loop controls how many times the inner loop executes (equal to the length of the array) while the inner loop compares neighboring elements and swaps them if the left element is greater than the right element.

gistlibby LogSnag