selection sort using array code example
Example 1: javascript selection sort
const selectionSort = array => {
const arr = Array.from(array);
for (let i = 0; i < arr.length - 1; i++) {
let minPos = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minPos]) {
minPos = j;
}
}
if (i !== minPos) {
[arr[i], arr[minPos]] = [arr[minPos], arr[i]];
}
}
return arr;
};
console.log(selectionSort([4, 9, 2, 1, 5]));
Example 2: selection sort javascript
let selectionSort = (arr) => {
let len = arr.length;
for (let i = 0; i < len; i++) {
let min = i;
for (let j = i + 1; j < len; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min !== i) {
let tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
}
return arr;
}