So, before I see your solution, I want to try and figure it out for myself. This is basically a "sort in place" problem. So any sorting algorithm that can be done in a for loop should be feasible. I could use a temporary String, as it's not strictly forbidden, but I guess it's against the spirit of the rules, so I'll avoid that.
Then the algorithm should be relatively simple: if you haven't seen a zero yet, carry on, if you do see a zero, make a note of where it is, the next non-zero you see move ahead of that zero.
So, before I see your solution, I want to try and figure it out for myself. This is basically a "sort in place" problem. So any sorting algorithm that can be done in a for loop should be feasible. I could use a temporary
String
, as it's not strictly forbidden, but I guess it's against the spirit of the rules, so I'll avoid that.I'll be doing a lot of swapping, so:
Then the algorithm should be relatively simple: if you haven't seen a zero yet, carry on, if you do see a zero, make a note of where it is, the next non-zero you see move ahead of that zero.
OK, you beat me this time! :D You're about 3x faster
Swapping the
toString()
s for two comparisons speeds it up a bit, but it still takes more than double the amount of time yours does.Removing the call to
swap
(but still swapping) makes them pretty much identical. I had no idea a function call could be so heavy.That's an interesting find, I also wasn't aware that a function call would have made it that much worse.
Well, to be fair, that's over 100000 iterations. But surprising none-the-less.