DEV Community

Cover image for Bubble Sort in JavaScript
Olga Lapovsky
Olga Lapovsky

Posted on • Edited on

Bubble Sort in JavaScript

๐Ÿ“ผ Explanation of Bubble Sort :

๐Ÿ’ป CODE :

function bubbleSort(array) {
  let isSorted = false;
  let arrayLength = array.length - 1;
  let temp;
  while (!isSorted) {
    isSorted = true;
    for (let i = 0; i < arrayLength; i++) {
      if (array[i] > array[i + 1]) {
        temp = array[i + 1];
        array[i + 1] = array[i];
        array[i] = temp;
        isSorted = false;
      }      
    }
    arrayLength--;
  }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • Best: ฮฉ(N)
  • Average: ฮ˜(Nยฒ)
  • Worst: ฮŸ(Nยฒ)

Space Complexity:

  • ฮŸ(1)

Top comments (0)