Counting Sort
동작 원리
1

2

3

4

5

6


구현
package sort;
public class CountingSort {
public static void main(String[] args) {
CountingSort countingSort = new CountingSort();
int[] A = {2, 5, 3, 0, 2, 3, 0, 3};
int[] sorted = countingSort.sort(A);
countingSort.printArray(sorted);
}
public void printArray(int[] A) {
for (int num : A) {
System.out.print(num + " ");
}
}
public int[] sort(int[] A) {
int n = A.length;
// 최대값 찾기
int k = getMax(A);
int[] count = new int[k + 1];
int[] output = new int[n];
// 각 요소의 빈도 계산
for (int i = 0; i < n; i++) {
count[A[i]]++;
}
// 누적 합 계산
for (int i = 1; i <= k; i++) {
count[i] += count[i - 1];
}
// 출력 배열에 정렬된 요소 배치
for (int i = n - 1; i >= 0; i--) {
output[count[A[i]] - 1] = A[i];
count[A[i]]--;
}
return output;
}
private int getMax(int[] A) {
int max = A[0];
for (int num : A) {
if (num > max) {
max = num;
}
}
return max;
}
}풀이
선택 가이드
시간 복잡도
장점
단점
Last updated
