+ 1
Segrigate 0,1,2 in an array in 0(N) time .can anyone tell why my code is not working for bigger array . like array of 17 đ˘
Please someone fix my code https://code.sololearn.com/cVC1R76EI0JN/?ref=app
3 Answers
+ 1
Put your 2 check before your 0 check, otherwise you can end up swapping a 0 in from the end after you've stopped looking for them (whereas the start of the array has already been sanitized)
+ 1
Short answer: because you're swapping, not pushing
Let's look at [1, 2, 0]:
* first = 0, last = 2
* i=0: it's not 0; it's not 2; no changes
* i=1: it's not 0; it IS 2, swap with the last member -- [1, 0, 2]; last = i, so we're done
* i=2: it's not 0; i > last, so we're done
Final array: [1, 0, 2]
Compare with the complementary example, [2, 0, 1], for 2 before 0.
If we naively process arr[1] first, you'd end up with the same problem. But we'll always have done arr[0] already, which means there can't be any 2s to the left of i, so we're ok.
0
Thank youđOrin Cook for helping me
But still i not understand why to put 2check before,
I mean if we iterate we will find either 0 or 2 ( only one while at a time) then why does it matter to put 2check beforđ¤