1const selectionSort = array => {
2 const arr = Array.from(array); // avoid side effects
3 for (let i = 0; i < arr.length - 1; i++) {
4 let minPos = i;
5 for (let j = i + 1; j < arr.length; j++) {
6 if (arr[j] < arr[minPos]) {
7 minPos = j;
8 }
9 }
10 if (i !== minPos) {
11 [arr[i], arr[minPos]] = [arr[minPos], arr[i]];
12 }
13 }
14 return arr;
15};
16
17console.log(selectionSort([4, 9, 2, 1, 5]));
18
1let selectionSort = (arr) => {
2 let len = arr.length;
3 for (let i = 0; i < len; i++) {
4 let min = i;
5 for (let j = i + 1; j < len; j++) {
6 if (arr[min] > arr[j]) {
7 min = j;
8 }
9 }
10 if (min !== i) {
11 let tmp = arr[i];
12 arr[i] = arr[min];
13 arr[min] = tmp;
14 }
15 }
16 return arr;
17}