Last active
November 6, 2016 22:33
-
-
Save patmood/4e94dc51286b528e58522c210d9909bc to your computer and use it in GitHub Desktop.
Javascript Bubble Sort
This file contains 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
// 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