Skip to content

Bubble sort implementation

Daisho Komiyama edited this page Jun 19, 2021 · 3 revisions

This is often the easiest to conceptualize and a natural way for the brain to think about sorting so it's typical to do bubble sort first. It's also amongst the least efficient in terms of a worst-case scenario.

With a nested for-loop

const bubbleSort = nums => {
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < nums.length - 1; j++) {
      if (nums[j] > nums[j+1]) {
        // Swaps left and right
        const temp = nums[j]
        nums[j] = nums[j+1]
        nums[j+1] = temp
      }
    }
  }

  return nums
}

With a do-while-loop

const bubbleSort = nums => {
  let swapped
  
  do {
    swapped = false
    for (let i = 0; i < nums.length; i++) {
      if (nums[i] > nums[i+1]) {
        const temp = nums[i]
        nums[i] = nums[i+1]
        nums[i+1] = temp
        swapped = true
      }
    }
  } while(swapped)

  return nums
}
Clone this wiki locally