Skip to content

Instantly share code, notes, and snippets.

@dagolinuxoid
Last active April 16, 2017 10:32
Show Gist options
  • Save dagolinuxoid/62ea07e11649536a94d1d6d74581e283 to your computer and use it in GitHub Desktop.
Save dagolinuxoid/62ea07e11649536a94d1d6d74581e283 to your computer and use it in GitHub Desktop.
JS | selectionSort && bubbleSort && insertionSort | it is my poor implementation ... I guess || maybe it's not that bad
//selection sort
function selectionSort(arr) {
let indexOfSmallestItem = 0;
// really? LOL
let j = 0;
let i = 0;
let placeholder;
while (j < arr.length) {
for ( ; i < arr.length; i++) {
// find smallest item in the array
if (arr[indexOfSmallestItem] > arr[i]) {
indexOfSmallestItem = i;
}
}
// swap between items
placeholder = arr[j];
arr[j] = arr[indexOfSmallestItem];
arr[indexOfSmallestItem] = placeholder;
// me: got it ? me: Of course I did, but it looks like sh1t.
indexOfSmallestItem = ++j;
i = j;
}
return arr;
}
console.log(selectionSort([3,2,1,4, -1, 121, 14, 32, 0, 99, 11]));
// bubble sort: it looks more appealing
function bubbleSort (arr) {
let buffer;
let swapCounter = true;
while (swapCounter) {
swapCounter = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
buffer = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = buffer;
swapCounter++;
}
}
}
return arr;
}
let array = [3, 2, 5, 12, 0, 4];
console.log(bubbleSort(array));
//insertion sort
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let buff = arr[i];
let counter = 0;
for (let j = i - 1; j > -1; j--) {
if (buff < arr[j]) {
arr[j + 1] = arr[j];
counter++;
} else {
break;
}
}
if (counter) {
arr[i - counter] = buff;
}
}
return arr;
}
let array = [5, 2, 1, 3, 6, 4, 12, 0, 44, 7];
console.log(insertionSort(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment