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 😢 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

14th May 2023, 12:09 PM
baibhav kumar
baibhav kumar - avatar
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)
14th May 2023, 2:37 PM
Orin Cook
Orin Cook - avatar
+ 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.
14th May 2023, 5:04 PM
Orin Cook
Orin Cook - avatar
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🤔
14th May 2023, 4:19 PM
baibhav kumar
baibhav kumar - avatar