Skip to content

Instantly share code, notes, and snippets.

@mrv1k
Last active May 5, 2017 03:56
Show Gist options
  • Save mrv1k/aec87b148dac3caca7ed019caa097bd7 to your computer and use it in GitHub Desktop.
Save mrv1k/aec87b148dac3caca7ed019caa097bd7 to your computer and use it in GitHub Desktop.
Simple sorting algorithms in JavaScript
var testArr = [4, 2, 6, 8, 1, 3, 7, 5];
function bubbleSort(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
let bubble = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = bubble;
}
}
}
}
bubbleSort(testArr);
var testArr = [4, 2, 6, 8, 1, 3, 7, 5];
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
var smallest = [arr[i]];
for (let j = i; j < arr.length; j++) {
if (smallest[0] >= arr[j]) {
smallest[0] = arr[j];
smallest[1] = j;
}
}
let temp = arr[i];
arr[i] = smallest[0];
arr[smallest[1]] = temp;
}
}
selectionSort(testArr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment