OneCompiler

Sort an array

189

let arr = [1, 3, -2, -5, 54, 23, 4, 0, -45];

// let arr = [20, 35, -15, 7, 55, 1, -22];

console.log(selectionSearch())

function selectionSearch() {
// body...
console.log(arr.length)
for(let lastUnsortedIndex = arr.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {
let maxValueIndex = 0;
for(let i = 1; i <= lastUnsortedIndex; i++) {
if(arr[i] < arr[maxValueIndex]) {
maxValueIndex = i;
}
}
if(maxValueIndex !== lastUnsortedIndex) {
swap(maxValueIndex, lastUnsortedIndex);
}
}
console.log(arr.length)
return arr;
}

function swap(i, j) {
let tmpValue = arr[i];
arr[i] = arr[j];
arr[j] = tmpValue;

return arr;
}