The code giving wrong output on the following test case.
TC: 2 0 2 1 1 0
Output: 0 0 1 2 1 2
By putting the last condition(for 2’s) in the beginning, it works. Why so?
The code giving wrong output on the following test case.
TC: 2 0 2 1 1 0
Output: 0 0 1 2 1 2
By putting the last condition(for 2’s) in the beginning, it works. Why so?
I didn’t get your doubt, can you elaborate?
If you have coded it, share the code as well.
#include using namespace std; int main() { int nums[] = {2,0,2,1,1,0}; int n = sizeof(nums)/sizeof(int); int low = 0; int hi = n-1; int mid = 0; while(mid <= hi){ if(nums[mid] == 0){ swap(nums[mid], nums[low]); mid++; low++; } if(nums[mid] == 1){ mid++; } if(nums[mid] == 2){ swap(nums[mid], nums[hi]); hi–; } } for(int i=0; i<n; i++) cout<<nums[i]<<" "; cout<<endl; }
this is the same code explained in the video. but it is giving wrong output on the test case which i have given
Please share it using ide.codingblocks.com , go there. Save your code and then save it. A special url will be generated when you will save your code, share that url with me.
but when i put the if condition written for 2’s(which is in the end) in the beginning, then it gives the correct output
are you able to see the code?
See now ->
It’s just because of the data flow. That’s why in last execution it wasn’t giving right answer. Using else if it will ensure it will check first, then second and then third. If first 2 are false. On the other hand all if makes sure to check all 3 conditions no matter if any of them is true or false.
Ohkk. I’ll dry run again with some other test cases and check. Thank you!
You can save your time by submitting your code here
ya i was submitting the code there only. Thanks btw!
If your doubt is solved can i mark it as resolved?
ya sure. Mark it as resolved.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.