This shows you the differences between two versions of the page.
| radix_sort [2016/06/07 12:37] – 만듦 ledyx | radix_sort [2016/06/07 13:02] (current) – 이전 ledyx | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | = Radix Sort (기수 정렬) = | ||
| - | 데이터 길이가 같을 때 사용 가능. | ||
| - | |||
| - | {{tag> | ||
| - | |||
| - | = 정수 = | ||
| - | <sxh java> | ||
| - | public static int[] radixSort(int[] arr, int maxLen) { | ||
| - | int bucketNum = 10; | ||
| - | |||
| - | int divFactor = 1; | ||
| - | |||
| - | Queue< | ||
| - | for (int j = 0; j < buckets.length; | ||
| - | buckets[j] = new LinkedList(); | ||
| - | |||
| - | for (int i = 0; i < maxLen; i++) { | ||
| - | |||
| - | for (int digitIndex = 0; digitIndex < arr.length; digitIndex++) { | ||
| - | // N번째 자리 숫자 추출 | ||
| - | int radix = (arr[digitIndex] / divFactor) % 10; | ||
| - | |||
| - | buckets[radix].offer(arr[digitIndex]); | ||
| - | } | ||
| - | |||
| - | int pos = 0; | ||
| - | for (int bucketIndex = 0; bucketIndex < bucketNum; bucketIndex++) { | ||
| - | while (!buckets[bucketIndex].isEmpty()) { | ||
| - | arr[pos] = buckets[bucketIndex].poll(); | ||
| - | pos++; | ||
| - | } | ||
| - | } | ||
| - | |||
| - | divFactor *= 10; | ||
| - | } | ||
| - | |||
| - | return arr; | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | = 문자열 = | ||
| - | <sxh java> | ||
| - | public static String[] radixSort(String[] arr, int maxLen) { | ||
| - | int bucketNum = ' | ||
| - | |||
| - | int charIndex = maxLen - 1; // | ||
| - | |||
| - | Queue< | ||
| - | for (int j = 0; j < buckets.length; | ||
| - | buckets[j] = new LinkedList(); | ||
| - | |||
| - | for (int i = 0; i < maxLen; i++) { | ||
| - | |||
| - | for (int digitIndex = 0; digitIndex < arr.length; digitIndex++) { | ||
| - | |||
| - | try { | ||
| - | // | ||
| - | String str = arr[digitIndex].toLowerCase(); | ||
| - | |||
| - | if(str.length() != maxLen) { | ||
| - | throw new Exception(" | ||
| - | } | ||
| - | |||
| - | int radix = str.charAt(charIndex) - ' | ||
| - | |||
| - | if(radix < 0 || radix > ' | ||
| - | throw new Exception(" | ||
| - | } | ||
| - | |||
| - | |||
| - | buckets[radix].offer(arr[digitIndex]); | ||
| - | } catch (Exception e) { | ||
| - | System.err.println(e.getMessage()); | ||
| - | return null; | ||
| - | } | ||
| - | |||
| - | } | ||
| - | |||
| - | int pos = 0; | ||
| - | for (int bucketIndex = 0; bucketIndex < bucketNum; bucketIndex++) { | ||
| - | while (!buckets[bucketIndex].isEmpty()) { | ||
| - | arr[pos] = buckets[bucketIndex].poll(); | ||
| - | pos++; | ||
| - | } | ||
| - | } | ||
| - | |||
| - | charIndex--; | ||
| - | } | ||
| - | |||
| - | return arr; | ||
| - | } | ||
| - | </ | ||