I have an exercise in which I have to sort the array as follows:
- numbers that divide 4 without a remainder will be the first in the array (for example, 4,8,12,16).
- numbers dividing 4 with a remainder of 1 will be the second in the array (1,5,9).
- numbers that divide 4 with the remainder of 2 will be the third in the array (2,6,10).
- numbers that divide 4 with a remainder of 3 will be the last in the array.
For example, the following array:
int []a={1,7,3,2,4,1,8,14}
will be:
4 8 1 1 2 14 3 7
order within groups does not matter.
I found a solution that works on O (n) complexity and O (1) space complexity.
However, it is ugly and moves around the array 3 times. I would like to get a more elegant solution.
This is my code:
int ptr=a.length-1; int temp=0, i=0; while (i<ptr){
It's important to know:
- I do not want the complexity of time to be worse than O (n), and the complexity of space is worse than O (1).
source share