I have a task involving two arrays - one named a, containing 5 values, and another named s which is currently empty. The objective is to identify the smallest value in array a, add it to array s, and then remove it from array a. Below is the code I have implemented:
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();
}
I am facing an issue where my program fails to properly remove the element from array a after adding it to array s.
When I remove the line a.splice(min, 1) and only keep s.push(a[min]), all the values from a end up in s. However, if I include both actions, the result I get is as follows:
s: [9, 23, 30]
a: [10, 26]
What I'm aiming for is:
s: [9, 10, 23, 26, 30]
a: []
I would appreciate any insights on why this is happening and how I can resolve it. Any assistance provided would be highly valued.