-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
65 lines (56 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Selection sort. (could also get implemented with the sort mapping function of the Array object)
*
* @param {string} sortOrder - 'asc' or 'desc'
* @param {Array<number>} array
*
* @returns {Array}
*/
export function selectionSort(sortOrder, array) {
const length = array.length;
let lowestItem;
// Iterate over each item of the array
for (let i = 0; i < length; i++) {
lowestItem = i;
// Iterate over each sub array item and detect the lowest value
for (let y = i + 1; y < length; y++) {
// Compare item one with item two depending on the configured sort order
if (compare(sortOrder, array[y], array[lowestItem])) {
lowestItem = y;
}
}
// Move lowest element to the first position of the array
swap(lowestItem, i, array);
}
return array;
}
/**
* Compares to items by the given sort order.
*
* @param {string} sortOrder - 'asc' or desc
* @param {number} itemOne
* @param {number} itemTwo
*
* @returns {boolean}
*/
function compare(sortOrder, itemOne, itemTwo) {
if (sortOrder === 'asc') {
return itemOne < itemTwo;
}
return itemOne > itemTwo;
}
/**
* Swaps two elements of an array and returns the array.
*
* @param {number} one
* @param {number} two
* @param {Array<number>} array
*
* @returns {Array}
*/
function swap(one, two, array) {
const tmp = array[one];
array[one] = array[two];
array[two] = tmp;
return array;
}