For a homework assignment, I need to write method which can sort array, the sort method should be efficient as possible.
- Beginning of the array will appear all the numbers that divide by 4 without remainder.
- Will be followed by all the numbers that divide by 4 with remainder of 1
- Will be followed by all the numbers that divide by 4 with remainder of 2
- At the end of the array will all the other numbers (those that divide by four with the remaining three).
I tried this set 4 pointers:
2 pointers At first the remainder of 0 and 1
2 pointers at the last of the array for the remainder of 2 and 3
This is what I could find so far (with problem of course), I appreciate your help !
public static void sortByFour (int[] arr)
{
int temp;
int noRemainderIndex = 0;
int remainder1Index = 1;
int remainder2Index = arr.length - 2;
int remainder3Index = arr.length - 1;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 4 == 0)
{
temp = arr[noRemainderIndex];
arr[noRemainderIndex] = arr[i];
arr[i] = temp;
noRemainderIndex++;
remainder1Index++;
}
else if (arr[i] % 4 == 1)
{
temp = arr[remainder1Index];
arr[remainder1Index] = arr[i];
arr[i] = temp;
remainder1Index++;
}
else if (arr[i] % 4 == 2)
{
temp = arr[remainder2Index];
arr[remainder2Index] = arr[i];
arr[i] = temp;
remainder2Index--;
}
else if (arr[i] % 4 == 3)
{
temp = arr[remainder3Index];
arr[remainder3Index] = temp = arr[i];
arr[i] = temp;
remainder3Index--;
remainder2Index--;
}
}
Array.sortmethod?