Skip to content

Instantly share code, notes, and snippets.

@dballowe7912
Created June 27, 2023 13:20
Show Gist options
  • Save dballowe7912/fdae786e0d6307f8bef06f9a6447971b to your computer and use it in GitHub Desktop.
Save dballowe7912/fdae786e0d6307f8bef06f9a6447971b to your computer and use it in GitHub Desktop.
function bubbleSort(arr) {
let temp;
let swapped = false
for (let i = 0; i < arr.length; i++) {
// If the current value is greater than its neighbor to the right
if (arr[i] > arr[i + 1]) {
// Swap those values
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp
swapped = true
}
}
// If you get to the end of the array and no swaps have occurred, return
if (!swapped) {
return arr
}
// Otherwise, repeat from the beginning
return bubbleSort(arr)
}
// bubbleSort([9, 3, 2, 6, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment