
배열 내 원소의 개수를 세어 위치를 결정하는 정렬 알고리즘
⇒ 각 원소가 몇 번 등장했는지를 카운팅한 후, 이를 이용해 정렬된 배열을 생성

const countingSort = (arr) => {
const max = Math.max(...arr);
const count = Array(max + 1).fill(0);
const result = Array(arr.length);
// 1. 카운트 배열 채우기
arr.forEach(num => count[num]++);
// 2. 누적합 변환
for (let i = 1; i <= max; i++) {
count[i] += count[i - 1];
}
// 3. 입력 배열을 역순으로 순회하면서 결과 배열 채우기
for (let i = arr.length - 1; i >= 0; i--) {
result[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
return result;
};
const testArr = [4, 2, 9, 1, 5, 6, 4, 2];
console.log(countingSort(testArr)); // [1, 2, 2, 4, 4, 5, 6, 9]