Radix Algorithm Understanding in Java -
below code radix algorithm www.sanfoundry.com. don't understand 3rd loop in while loop: why int must counted inversely , how loop works resign ordered elements b[]. , 1 more question, if regard number based 2 next similar code? , there possibility modify code mixture of positive , negative numbers?
public static void radixsort(int[] input){ final int n = input.length; int exp = 1; int[] b = new int[n]; int max = input[0]; for(int = 1; < n; i++){ if(max <= input[i]) max = input[i]; } while(max / exp > 0){ int[] bucket = new int[10]; for(int = 0; < n; i++) bucket[(input[i] / exp ) % 10]++; for(int = 1; < 10; i++) bucket[i] += bucket[i - 1]; for(int = n - 1; >= 0; i--) b[--bucket[(input[i] / exp) % 10]] = input[i]; for(int = 0; < n; i++) input[i] = b[i]; exp *= 10; } }
the 3rd loop inversed create sorting stable.
changing base of operations 2 easy: alter number of buckets 2, replace exp *= 10
exp *= 2
, (input[i] / exp) % 10
(input[i] / exp) % 2
.
to deal negative numbers, can sort negative numbers separately using absolute value key , merge reversed result sorted non-negative numbers.
and looks there bug in code snippet: should int[] b = new int[n];
instead of int[] b = new int[10];
java algorithm
No comments:
Post a Comment