Skip to content

Instantly share code, notes, and snippets.

@vincentriemer
Last active August 28, 2016 23:13
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 vincentriemer/650de820c7408c660115ede5758fea8b to your computer and use it in GitHub Desktop.
Save vincentriemer/650de820c7408c660115ede5758fea8b to your computer and use it in GitHub Desktop.
sorting
import swap from './swap.js'; ///++**Bubble Sort**++
export default function(input, compare) {
for (let i = 0; i < input.length; i++) {
let swapped = false;
for (let j = 0; j < input.length - (i + 1); j++) {
if (!compare(input[j], input[j + 1])) {
swap(j, j + 1, input);
swapped = true;
}
}
if (!swapped)
return input;
}
return input;
}
import compare from './compare.js';
import input from './input.js';
import bubbleSort from './bubbleSort.js';
import insertionSort from './insertionSort.js';
import selectionSort from './selectionSort.js';
const sortingAlgorithms = [
bubbleSort,
insertionSort,
selectionSort
];
const sortingChoices = [
"BubbleSort",
"InsertionSort",
"SelectionSort"
];
const choice = 2;
const sortingAlgorithm = sortingAlgorithms[choice];
const storingAlgorithmName = sortingChoices[choice];
const testInput = input(36);
sortingAlgorithm(Array.from(testInput), compare);
export default function compare (a, b) {
return a < b;
}
export default function(length) {
let output = [];
for (let i = 0; i < length; i++) {
output.push(~~(Math.random() * 50));
}
return output;
}
import swap from './swap.js'; ///++**Insertion Sort**++
export default function (input, compare) {
for (let i = 0; i < input.length - 1; i++) {
if (!compare(input[i], input[i+1])) {
swap(i, i+1, input);
for (let j = i; j > 0; j--) {
if (!compare(input[j-1], input[j])) {
swap(j-1, j, input);
} else {
break;
}
}
}
}
return input;
}
import swap from './swap.js' ///++**Selection Sort**++
function findMinIndex (array, startingIndex) {
let minIndex = -1, minValue = Number.POSITIVE_INFINITY;
for (let i = startingIndex; i < array.length; i++) {
if (array[i] < minValue) {
minIndex = i;
minValue = array[i];
}
}
return minIndex;
}
export default function(input, compare) {
for (let i = 0; i < input.length - 1; i++) {
const minIndex = findMinIndex(input, i);
if (minIndex != i) {
swap(minIndex, i, input);
}
}
return input;
}
export default function (indexA, indexB, array) {
const tempA = array[indexA];
array[indexA] = array[indexB];
array[indexB] = tempA;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment