function newsort(arr, left, right){
for(var i= left; i < right; ++i){
var min = i;
for (var j = i; j < right; ++j){
if (arr[min] > arr[
Eloquent solution:
const selectionSort = (items) => {
items.forEach((val, i, arr) => {
const smallest = Math.min(...arr.slice(i))
const smallestIdx = arr.indexOf(smallest)
if (arr[i] > arr[smallestIdx]) {
const temp = arr[i]
arr[i] = arr[smallestIdx]
arr[smallestIdx] = temp
}
})
return items
}
Standard solution:
const selectionSort = (arr) => {
for (let i=0; i <= arr.length-1; i++) {
// find the idnex of the smallest element
let smallestIdx = i
for (let j=i; j <= arr.length-1; j++) {
if (arr[j] < arr[smallestIdx]) {
smallestIdx = j
}
}
// if current iteration element isn't smallest swap it
if (arr[i] > arr[smallestIdx]) {
let temp = arr[i]
arr[i] = arr[smallestIdx]
arr[smallestIdx] = temp
}
}
return arr
}
Testing:
console.log( // [14, 29, 56, 72, 92, 98]
selectionSort([29, 72, 98, 14, 92, 56])
)