× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

What is the easiest way to sort an array into 4 sections by 4 factors?

James Jensen
Feb 10, 2015
<p>What you're describing isn't a <em>sort</em> at all, but a <em>grouping</em>. Since you've got a fixed number of slots (4) and the mod is incremental (it will always be 0, 1, 2, or 3), that makes things easy.</p> <p>Just create an array for your sections with a length of 4, and then:</p> <pre><code>List&lt;Integer&gt;[] sections = new List&lt;Integer&gt;[4]; for(int i = 0; i &lt; 4; i++) sections[i] = new ArrayList&lt;Integer&gt;(); for(int i : collection) sections[i%4].add(i); </code></pre> <h2>Update</h2> <p>After looking at the question again, I'm wondering if I was right. If you just want to sort the original array so that certain numbers go first, rather than actually grouping it into pieces, you can use something like this:</p> <pre><code>Arrays.sort(collection, new Comparator&lt;Integer&gt;() { @Override public int compare(Integer a, Integer b) { return a % 4 &lt; b % 4; } }); </code></pre> <p>(Forgive me if this doesn't compile: my Java is a bit rusty)</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/23872148/What%20is%20the%20easiest%20way%20to%20sort%20an%20array%20into%204%20sections%20by%204%20factors?/23872236">Stack Overflow</a>.</p>
comments powered by Disqus