Created
June 27, 2023 13:20
-
-
Save dballowe7912/fdae786e0d6307f8bef06f9a6447971b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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