Skip to content

Instantly share code, notes, and snippets.

@t9toqwerty
Last active November 29, 2019 10:53
Show Gist options
  • Save t9toqwerty/ab81415dd5ed7860b22d0858e0220861 to your computer and use it in GitHub Desktop.
Save t9toqwerty/ab81415dd5ed7860b22d0858e0220861 to your computer and use it in GitHub Desktop.
package app;
import java.util.Iterator;
import java.util.LinkedList;
/**
* Sorter
*/
public class Sorter {
public void radixSort(int[] nums) {
LinkedList[] bin = new LinkedList[nums.length];
int maxNum = this.findMax(nums);
int radix = this.findRadix(maxNum);
for (int i = 0; i < radix; i++) {
// Reset Bin
for (int p = 0; p < bin.length; p++) {
bin[p] = new LinkedList<Integer>();
}
for (int j = 0; j < nums.length; j++) {
int position = (int) ((nums[j] / (Math.pow(10, i))) % 10);
bin[position].add(nums[j]);
}
int k = 0;
for (int j = 0; j < bin.length; j++) {
Iterator it = bin[j].iterator();
while (it.hasNext()) {
int temp = (int) it.next();
nums[k] = temp;
k++;
}
}
}
}
private int findRadix(int maxNum) {
int radix = 0;
while (maxNum != 0) {
maxNum = maxNum / 10;
radix++;
}
return radix;
}
private int findMax(int[] nums) {
int max = nums[0];
for (int i = 0; i < nums.length; i++) {
if (max < nums[i]) {
max = nums[i];
}
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment