Sorting arrays in java
Posted
by user360706
on Stack Overflow
See other posts from Stack Overflow
or by user360706
Published on 2010-06-07T18:23:19Z
Indexed on
2010/06/07
18:32 UTC
Read the original article
Hit count: 230
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?
© Stack Overflow or respective owner