알고리즘 - Sort the odd
30 Aug 2019문제
You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn’t an odd number and you don’t need to move it. If you have an empty array, you need to return it.
예시
sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4];
풀이과정
- 홀수만 골라서 정렬해야 함
- 정렬방법 중 selection sort가 적합하다고 판단
code
function sortArray(array) {
for (let i = 0; i < array.length; i++) {
let minIndex = i;
let temp;
for (let j = i + 1; j < array.length; j++) {
if (!(array[i] % 2)) break;
if (array[minIndex] > array[j] && array[j] % 2) {
minIndex = j;
}
}
temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
return array;
}