Skip to content

Commit 8a80063

Browse files
authored
Merge pull request #38 from Data-Structure-Study/yoonexample
기수정렬 구현완료
2 parents b015594 + e6082c8 commit 8a80063

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package sort;
2+
3+
import queue.LinkedListQueue;
4+
import queue.Queue;
5+
6+
public class RadixSort {
7+
8+
private static final int BUCKET_NUM = 10;
9+
10+
public void sort(int[] array, int maxLength) {
11+
int divFac = 1;
12+
Queue<Integer>[] buckets = new Queue[BUCKET_NUM];
13+
14+
// 버킷 배열 초기화
15+
for (int i = 0; i < BUCKET_NUM; i++) {
16+
buckets[i] = new LinkedListQueue<>();
17+
}
18+
19+
// 가장 긴 데이터의 길이만큼 반복
20+
for (int i = 0; i < maxLength; i++) {
21+
// 정렬 대상 수의 개수만큼 반복
22+
for (int num : array) {
23+
// N번째 자리의 숫자 추출
24+
int radix = (num / divFac) % 10;
25+
26+
// 추출한 숫자에 위치하도록 데이터 저장
27+
buckets[radix].enqueue(num);
28+
}
29+
30+
// 버킷 수 만큼 반복
31+
for (int j = 0; j < BUCKET_NUM; j++) {
32+
// 버킷에 저장되어 있는 것을 순서대로 꺼내서 다시 array에 저장
33+
int arrayIndex = 0;
34+
while (!buckets[j].isEmpty()) {
35+
array[arrayIndex++] = buckets[j].dequeue();
36+
}
37+
}
38+
39+
// N번째 자리 숫자를 추출할 수 있도록 변경
40+
divFac *= 10;
41+
}
42+
}
43+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package sort;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.DisplayName;
6+
import org.junit.jupiter.api.Test;
7+
8+
class RadixSortTest {
9+
10+
@Test
11+
@DisplayName("기수_정렬_테스트")
12+
void 기수_정렬_테스트() {
13+
int[] array = {13, 212, 14, 7141, 10987, 6, 15};
14+
int maxLength = 5;
15+
16+
RadixSort radixSort = new RadixSort();
17+
radixSort.sort(array, maxLength);
18+
assertThat(array).containsExactly(6, 13, 14, 15, 212, 7141, 10987);
19+
}
20+
}

0 commit comments

Comments
 (0)