I read time complexity of radix sort is O(wn) or O(n log n), if all n numbers are distinct. After implementation it look to me as if I have implemented radix sort which has time complexity of O(n ^2). Please take a look at my implementation and suggest, if there is some implementation problem or my observation about time complexity is wrong.
Please note: I have hard coded few values for simplicity to sort 3 digit numbers only.
private void LSBSort(int[] arr) {
_LSBSort(arr, 1);
}
private void _LSBSort(int[] arr, int divisor) {
Deque[] deques = new Deque[10];
for(int i = 0 ; i < arr.length ; i++) {
int mod = (arr[i] /divisor ) % 10;
if (deques[mod] == null) {
deques[mod] = new ArrayDeque<>();
}
deques[mod].add(arr[i]);
}
divisor *= 10;
if (divisor > 1000) {
return;
}
int cursor = 0;
for (int i = 0 ; i < 10 ; i++) {
if (deques[i] != null) {
for (int j = 0 ; j <= deques[i].size() ; j++) {
cursor = cursor + j;
arr[cursor] = (int)deques[i].pollFirst();
}
cursor++;
}
}
_LSBSort(arr, divisor);
}
_LSBSort
takes time O(n), and it is repeated w times. \$\endgroup\$deques[i]
contains si items, so iterating over it takes time O(si). Then the outerfor
loop takes time O(s1) + O(s2) ... + O(s10) = O(s1 + s2 + ... + s10). But since each item occurs in exactly one deque, we know s1 + s2 + ... + s10 = n. Conclude the loop takes time O(n). \$\endgroup\$