I'm struggling to understand how the following algorithm (in Java) works.
private static void sort(int[] values, k)
{
int mask = 0x00000001 << k;
int insertIndex = 0;
int ArrayList<Integer> big = new ArrayList<Integer>();
for (int i = 0; i < values.length; ++i) {
if ((values[i] & mask) == 0)
values[insertIndex++] = values[i];
else
big.add(values[i]);
}
for (int i = 0; i < big.size(); ++i)
values[insertIndex++] = big.get(i);
}
public static void sort(int[] values)
{
for (int i = 0; i < 31; ++i)
sort(values, i);
}
Here's what I undestand so far:
At first 0x00000001 (32 bit?) gets left-shifted by k. So mask now is some other number. Then we're checking if current value values[i] added with mask using Binary-And operator equals to 0.
I can't understand the role of (values[i] & mask) == 0 clause. Second for-loop messing with my head also. And why are we iterating in public static void sort(int[] values) only 31 times?
This algorithm doesn't sort negative integers correctly. How so? How can it be modified so that negative integers get sorted too?
It is said that this algorithm uses similar concepts of one the well-known sorting algorithms. Like Heap-sort, Insertion Sort, Quick-sort, Merge-Sort, Bucket-Sort or Radix-Sort. I eliminated the possibility of Quick-sort, because it uses partitions and recursion. Merge sort uses recursion and merges sub-arrays, so I eliminated it too. Insertion-Sort isn't likely to be the one either, because of the drastic time-complexity difference. Insertions sort O(n^2) and given algorithm is O(n). Bucket-sort doesn't actually sort anything, it just divides array in sub-arrays, which then can be sorted using some sorting algorithm. Heap-sort is comparison-based algorithm, and the given algorithms doesn't look like one. So the only possibility that's left is Radix-Sort, which is not a comparison-based algorithm. So my best bet is that the given algorithm is similar to Radix sort. Am I right or am I hopelessly lost?
insertIndex?private static void sortfunction. I forgot to initialize intinsertIndex. Fixed.