I have just tested both methods and overall the counting then filling is slower, although for an array size of 10.000.000 the difference is a mere 50ms at most.
I have also tried Arrays.sort, and it is about twice as slow as the second method, and 33% slower than the first. This is logically, because it cannot use the fact that the array only stores zeros and ones. [ September 04, 2007: Message edited by: Rob Prime ]
So I think Gaurav's solution is best in this case.
Joined: Aug 05, 2005
Rob - you don't need to swap the values in the two elements because you already know the values. i.e. you can change the last part of the loop to
Although you should also check in the two inner while loops that the index is not negative, to handle the case where the array contains all zeros or all ones. Alternatively you could just put the outer while loop in a try/catch IndexOutOfBoundsException block. [ September 04, 2007: Message edited by: Joanne Neal ]
Joined: Feb 05, 2003
In the counting solution, it is also not needed to count the 1's. Just the 0's and the total length will do.
subject: what's the best way to sort primitive array ?