# Graphical sorting algorithm-selection sorting (javascript)

From: klh2333's github

## Algorithm principle

1. Select a current value and record its subscript as the initial minIndex
2. From the current value to traverse, if the traversed value is smaller than the current value, then record its subscript and assign it to minIndex
3. After a round of looping, minIndex corresponds to the subscript of the minimum value
4. Exchange the minimum value and the current value, and then continue the above operation

## Algorithm diagram

Suppose you want to sort [4, 3, 2, 1] from small to large: It can be found that the outermost layer only needs three rounds of loops . At the end of the last round of loops, the "4" stands alone on the far right, and the others They are all sorted, and there is no need to look for minIndex anymore.

## javascript code

``````/**
*
*
*
*/
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) { //  minIndex
let minIndex = i; //
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) { //
minIndex = j;
}
}
//  minIndex
if (minIndex !== i) {
//
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
}
}
return arr;
}

//
let testArr = [9, 4, 6, 8, 1, 3, 2, 5];
console.log(selectionSort(testArr));

``````