Linear time solution
The most asymptotically effective way to do this would be to use a sorting bucket .
- You have 4 baskets, one for each of the matching classes modulo 4.
- Scan the numbers in the array once
- Put each number in the right bucket
- Then build the output array
- First enter all the numbers from bucket 0, then everything from bucket 1, then bucket 2, then bucket 3
Thus, it sorts the numbers in O(N) , which is optimal. The key here is that, sorting by numbers modulo 4, only 4 numbers are sorted in order: 0, 1, 2, 3.
Illustrative Solution with List
Here the implementation of the above algorithm is implemented (for the general modulo M ) using List and for each for clarity. Ignore the untested throw warning, just focus on understanding the algorithm.
import java.util.*; public class BucketModulo { public static void main(String[] args) { final int M = 4; List<Integer> nums = Arrays.asList(13,7,42,1,6,8,1,4,9,12,11,5); List<Integer>[] buckets = (List<Integer>[]) new List[M]; for (int i = 0; i < M; i++) { buckets[i] = new ArrayList<Integer>(); } for (int num : nums) { buckets[num % M].add(num); } nums = new ArrayList<Integer>(); for (List<Integer> bucket : buckets) { nums.addAll(bucket); } System.out.println(nums);
Once you fully understand the algorithm, translating this into using arrays (if necessary) is trivial.
see also
Special note to %
The caveat that numbers are non-negative is significant because % NOT a modular operator because it is mathematically defined; this is the remainder operator.
System.out.println(-1 % 2);
References
source share