Skip to content

Instantly share code, notes, and snippets.

@patmood
Last active November 6, 2016 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patmood/4e94dc51286b528e58522c210d9909bc to your computer and use it in GitHub Desktop.
Save patmood/4e94dc51286b528e58522c210d9909bc to your computer and use it in GitHub Desktop.
Javascript Bubble Sort
// Bubble sort
// Time: O(n^2)
// Space: O(1)
const test = require('assert').deepEqual
const bubbleSort = (arr) => {
// Create a variable to store values temporarily - Only needs to be created once for O(1) space complexity
let temp = null
// Step over each element of array
for (let i = 0; i < arr.length; i++) {
// Loop over all previous elements and swap position if current element is smaller
for (let j = i; j > 0; j--) {
if (arr[j - 1] > arr[j]) {
// actual swapping of values
temp = arr[j-1]
arr[j-1] = arr[j]
arr[j] = temp
}
}
}
return arr
}
test(bubbleSort([1]), [1])
test(bubbleSort([2,1]), [1, 2])
test(bubbleSort([2,1,0]), [0,1,2])
test(bubbleSort([23,-2,0.23,2,1,0]), [-2,0,0.23,1,2,23])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment