더북(TheBook)

5.2.1 선택 정렬 구현

다음은 자바스크립트로 구현한 선택 정렬이다.

function selectionSort(array) {
    for(let i = 0; i < array.length - 1; i++) {
        let lowestNumberIndex = i;
        for(let j = i + 1; j < array.length; j++) {
            if(array[j] < array[lowestNumberIndex]) { 
                lowestNumberIndex = j;
            } 
        }

        if(lowestNumberIndex != i) {
            let temp = array[i];
            array[i] = array[lowestNumberIndex]; 
            array[lowestNumberIndex] = temp;
        } 
    }
    return array;  
}

한 줄씩 나눠서 살펴보자.