Write a static method in Java:
public static void sortByFour (int[] arr)
That receives as a parameter an array full of non-negative numbers (zero or positive) and sorts the array in the following way:
In the beginning of the array all the numbers that are divisible by four will appear.
After them all the numbers in the array that divide by 4 with a remainder of 1 will appear.
After them all the numbers in the array that divide by 4 with a remainder of 2 will appear.
In the end of the array all the rest numbers (those which divide by 4 with the remainder 3) will appear.
(The order of the numbers in each group doesn't matter.)
The method must be as efficient as possible.
The following is what I wrote, but unfortunately it doesn't work well... :(
public static void swap( int[] arr, int left, int right )
{
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
public static void sortByFour( int[] arr )
{
int left = 0;
int right = ( arr.length - 1 );
int mid = ( arr.length / 2 );
while ( left < right )
{
if ( ( arr[left] % 4 ) > ( arr[right] % 4 ) )
{
swap( arr, left, right );
right--;
}
if ( ( arr[left] % 4 ) == ( arr[right] % 4 ) )
left++;
else
left++;
}
}
How do I fix or rewrite my code so that it will work well?