Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Created October 28, 2025 15:49
Show Gist options
  • Select an option

  • Save mustafadalga/61e0837ffd248506505cd7a086860303 to your computer and use it in GitHub Desktop.

Select an option

Save mustafadalga/61e0837ffd248506505cd7a086860303 to your computer and use it in GitHub Desktop.
Bubble sort is a simple sorting algorithm which compares and swaps adjacent elements such that after every iteration over the array, one more element will be ordered/correctly placed, starting from the largest.
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
let swapped = false
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] >= arr[j + 1]) {
swapped = true
const temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
if (!swapped) {
break
}
}
return arr
}
console.log(bubbleSort([ 9, 3, 6, 2, 1, 11 ]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment