I have a trouble with finding a right value for sorting with radix sorting algorithm. I have implemented it right, but I have an issue with negatives. I tried just to reverse value with a binary. It helped me a little, but negatives are in ascending order instead of being in descending order. Funniest thing is that sorting works fine with floating points and signed integers.
Here is my function to build a key for sorting:
uint32_t SortKeyToU32(int Value)
{
uint32_t Result = (uint32_t)Value;
if(Result & 0x80000000)
{
Result = ~Result;
}
else
{
Result |= 0x80000000;
}
return Result;
}
And here is my sorting function:
void RadixSort(int** Array, int Size)
{
int* Dest = new int[Size];
int* Source = *Array;
memset(Dest, 0, Size*sizeof(int));
for(int Bit = 0;
Bit < 32;
Bit += 8)
{
uint32_t ArrayOfValues[256] = {};
for(int Index = 0;
Index < Size;
++Index)
{
uint32_t SortKey = SortKeyToU32(Source[Index]);
uint32_t Key = (SortKey >> Bit) & 0xFF;
++ArrayOfValues[Key];
}
int Sum = 0;
for (int Index = 0;
Index < ArraySize(ArrayOfValues);
++Index)
{
uint32_t Count = ArrayOfValues[Index];
ArrayOfValues[Index] = Sum;
Sum += Count;
}
for(int Index = 0;
Index < Size;
++Index)
{
uint32_t SortKey = SortKeyToU32(Source[Index]);
uint32_t Key = (SortKey >> Bit) & 0xFF;
Dest[ArrayOfValues[Key]++] = Source[Index];
}
int* Temp = Source;
Source = Dest;
Dest = Temp;
}
}
But how can I deal with sorting signed integers? Sorry if it is looks obvious. Thanks.
EDIT. Here is sample array input: 1, 6, 9, 2, 3, -4, -10, 8, -30, 4
Output: -4, -10, -30, 1, 2, 3, 4, 6, 8, 9