답지 보기 전 내 풀이
function solution(unsorted) {
function swap(former, latter) {
const temp = unsorted[former];
unsorted[former] = unsorted[latter];
unsorted[latter] = temp;
}
for (let i = 0; i < unsorted.length; i++) {
for (let j = i; j < unsorted.length; j++)
if (unsorted[j] > unsorted[j + 1]) swap(j, j + 1);
}
return unsorted;
}
const result = solution([13, 5, 11, 7, 23, 15]);
console.log(result);
- 선택 정렬이 아닌 버블 정렬에 가깝고 그마저도 불필요한 순회를 포함한 풀이 ㅠ
강의 반영한 풀이
function solution(unsorted) {
for (let i = 0; i < unsorted.length - 1; i++) {
let min = unsorted[i];
let indexToBeSwapped;
for (let j = i + 1; j < unsorted.length; j++)
if (min > unsorted[j]) {
min = unsorted[j];
indexToBeSwapped = j;
}
if (indexToBeSwapped)
[unsorted[i], unsorted[indexToBeSwapped]] = [
unsorted[indexToBeSwapped],
unsorted[i],
];
}
return unsorted;
}
const result = solution([13, 5, 11, 7, 23, 15]);
console.log(result);
- 아래 풀이가 swap 연산도 훨씬 적게 수행하고 논리도 명확하다.