1
0
Fork 0

Add sorting functions

This commit is contained in:
Timothy Warren 2019-07-26 16:45:59 -04:00
parent 57cfa8ad19
commit d3a55cd029
1 changed files with 44 additions and 0 deletions

44
src/sorting.js Normal file
View File

@ -0,0 +1,44 @@
function swap (items, firstIndex, secondIndex) {
let temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
export function bubbleSort (items) {
let len = items.length;
let stop = 0;
for (let i = 0; i < len; i++) {
for (let j = 0; stop=len-i, j < stop; j++) {
if (items[j] > items[j+1]) {
swap(items, j, j+1);
}
}
}
return items;
}
export function selectionSort (items) {
let len = items.length;
let min = 0;
let j = 0;
for (let i = 0; i < len; i++) {
min = i;
// Check to see if anything is smaller
for (j=i+1; j < len; j++) {
if (items[j] < items[min]) {
min = j;
}
}
// If the minimum isn't where it should be, swap it
if (i !== min) {
swap(items, i, min);
}
}
return items;
}