bubblesort in javascript

Here's an example implementation of the bubble sort algorithm in JavaScript:

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

// Example usage:
var arr = [5, 3, 8, 4, 2];
console.log(bubbleSort(arr)); // Output: [2, 3, 4, 5, 8]
378 chars
18 lines

This code defines a function called bubbleSort which takes an array as input, and returns the sorted array using bubble sort algorithm. The function uses two nested loops to iterate over the array and compare adjacent elements. If the elements are out of order, they are swapped. After each inner loop iteration, the largest element "bubbles up" to the end of the array. The sorting process is repeated until the array is sorted.

gistlibby LogSnag