Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
standard input/output: 2s/128000 kB

Given an array A of size N containing 0's, 1's and 2's. The task is to segregate the 0's, 1's and 2's in the array as all the 0's should appear in the first part of the array, 1's should appear in middle part of the array and finally all the 2's in the remaining part of the array.

Note: Do not use inbuilt sort function. Try to solve in O(N) per test case
Input
The first line contains an integer T denoting the total number of test cases. Then T testcases follow.
Each testcases contains two lines of input. The first line denotes the size of the array N.
The second lines contains the elements of the array A separated by spaces.

Constraints:
1 <= T <= 100
1 <= N <= 100000
0 <= Ai <= 2

Sum of N for each test case does not exceed 10^5
Output
For each testcase, in a newline, print the sorted array.

example

Input :
2
5
0 2 1 2 0
3
0 1 0

Output:
0 0 1 2 2
0 0 1

Explanation:
Testcase 1: After segragating the 0s, 1s and 2s, we have 0 0 1 2 2 which shown in the output.
Testcase 2: For the given array input, output will be 0 0 1.

What I have tried:

i have try to 9 times but big error in show my program.
Posted
Updated 23-May-22 2:58am
v2
Comments
Dave Kreskowiak 18-Dec-21 0:00am    
We can't help you if you don't show your code and the error messages you're getting.
Patrice T 18-Dec-21 2:10am    
You have a secret error in your secret code.
Try to show your code.

Hint: how many methods do you know that sort an array in O(N) ?
 
Share this answer
 
While we are more than willing to help those that are stuck, that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

Just posting your homework question and saying "I tried" isn't going to get you anywhere.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900