I was given a task to sort an array that is filled with (non negative) integers.
They should be sorted such that the output is in the following order:
- Numbers where the remainder of them divided by 4 is 0
- Numbers where the remainder of them divided by 4 is 1
- Numbers where the remainder of them divided by 4 is 2
- Numbers where the remainder of them divided by 4 is 3
I tried to write a simple algorithm that should work at O(n) (the task is to write the code efficiently).
But I think it's a mess, a few cases didn't work (for example when I tried an array where the first few numbers have remainders of 3).
Any suggestion on how to fix it or a better way of doing this?
public static void sortByFour(int[] arr)
{
int zeroR = -1, oneR = 0, twoR = arr.length-1, threeR = arr.length;
do
{
if (arr[oneR]%4==1)
oneR++;
else if (arr[oneR]%4==0)
{
zeroR++;
int temp = arr[oneR];
arr[oneR] = arr[zeroR];
arr[zeroR] = temp;
oneR++;
}
else if (arr[oneR]%4==2)
{
twoR--;
int temp = arr[oneR];
arr[oneR] = arr[twoR];
arr[twoR] = temp;
}
else if (arr[oneR]%4==3)
{
threeR--;
int temp = arr[oneR];
arr[oneR] = arr[threeR];
arr[threeR] = temp;
}
} while (oneR < threeR && oneR < twoR);
}