I have two arrays - a, with 5 values and s which is empty. What I have to do is to find the smallest value in a, add it to s and after adding it to s, to delete it from a. Here is my code:
class Sorting {
constructor () {
let getArr = document.getElementById('t');
}
findMin () {
let a = [23, 30, 9, 10, 26];
let s = [];
for (let i = 0; i < a.length; i++) {
let min = i;
for (let j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
s.push(a[min]);
a.splice(min, 1);
if (i !== min) {
let x = a[i];
a[i] = a[min];
a[min] = x;
}
}
console.log(s)
console.log(a)
}
}
function main() {
let p = new Sorting ();
p.findMin();
}
What I'm unable to do is to make my program delete the element from a properly after adding it to s.
If I delete the line a.splice(min, 1) and just leave s.push(a[min]), I get all the values from a into s. If I leave them both however, that's what I get as a result:
s: [9, 23, 30]
a: [10, 26]
And I want to get:
s: [9, 10, 23, 26, 30]
a: []
Can anyone please tell me why I get this and how can I fix it? Any help would be greatly appreciated.
s = a.sort((a,b) => a - b); a = [];?