Add sorting functions
This commit is contained in:
parent
57cfa8ad19
commit
d3a55cd029
44
src/sorting.js
Normal file
44
src/sorting.js
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user