Skip to content

Instantly share code, notes, and snippets.

@netpoetica
Created April 24, 2017 15:33
Show Gist options
  • Save netpoetica/0164db4227daf441122d80353f2ea2ec to your computer and use it in GitHub Desktop.
Save netpoetica/0164db4227daf441122d80353f2ea2ec to your computer and use it in GitHub Desktop.
function bubbleSort (arr) {
var left,
right,
swapped;
do {
swapped = false;
for (var i = 0; i < arr.length - 1; i++) {
left = arr[i];
right = arr[i + 1];
if (left > right) {
arr[i] = right;
arr[i + 1] = left;
swapped = true;
}
}
} while (swapped);
}
[
{
input: [43, 2, 29, 1, 22],
expected: [1, 2, 22, 29, 43]
},
{
input: [5,4,3,2,1],
expected: [1, 2, 3,4,5]
}
].forEach(function (data) {
bubbleSort(data.input);
console.log(data.input.toString() === data.expected.toString() ? true : data.input + ' should be ' + data.expected);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment