Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

Here is an example of a bubble sort function in JavaScript:

function bubbleSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        // swap arr[j] and arr[j+1]
        let temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }
  return arr;
}

This function takes an array as an argument and sorts it in ascending order using the bubble sort algorithm. The outer loop iterates through the array and the inner loop compares each pair of adjacent elements and swaps them if they are in the wrong order. The function then returns the sorted array.

Also Read:

Categorized in: