Sorting arrays in java
- by user360706
Write a static method in Java :
public static void sortByFour (int[] arr)
That receives as a paramater 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 devide by four without a remainder will appear.
After them all the numbers in the array that devide by 4 with a remainder of 1 will appear.
After them all the numbers in the array that devide by 4 with a remainder of 2 will appear.
In the end of the array all the rest numbers (those who divide by 4 with the remainder 3) will appear.
(The order of the numbers in each group doesn't matter)
The method must be the most efficient it can.
This 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++;
}
}
Can someone please help me by fixing my code so that it will work well or rewriting it?