-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
69 lines (57 loc) · 1.93 KB
/
script.js
File metadata and controls
69 lines (57 loc) · 1.93 KB
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
66
67
68
69
const sortButton = document.getElementById("sort");
const sortInputArray = (event) => {
event.preventDefault()
const inputValues = [...document.getElementsByClassName("values-dropdown")].map((dropdown) => Number(dropdown.value));
// the following line to test with a different sorting algorithm
// Change the assigned value of sortedValue to the algorithm you want to use/test [ bubbleSort, selectionSort, insertionSort] or use the in=bulit sort method that is currently commented out
const sortedValues = insertionSort(inputValues);
// const sortedValues = inputValues.sort((a, b) => {
// return a - b;
// });
updateUI(sortedValues);
}
const updateUI = (array = []) => {
array.forEach((num, i) => {
const outputValueNode = document.getElementById(`output-value-${i}`)
outputValueNode.innerText = num
})
};
const bubbleSort = (array) => {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
const temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
const selectionSort = (array) => {
for (let i = 0; i < array.length; i++) {
let minIndex = i;
for (let j = i + 1; j < array.length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
const temp = array[i]
array[i] = array[minIndex]
array[minIndex] = temp
}
return array;
}
const insertionSort = (array) => {
for (let i = 1; i < array.length; i++) {
const currentValue = array[i];
let j = i - 1;
while (j >= 0 && array[j] > currentValue) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = currentValue;
}
return array;
}
sortButton.addEventListener("click", sortInputArray)