Sort Array

Moderate
0/80
Average time to solve is 15m
profile
Contributed by
20 upvotes
Asked in companies
Tata Consultancy Services (TCS)BNY MellonAdobe

Problem statement

You are given an array consisting of 'N' positive integers where each integer is either 0 or 1 or 2. Your task is to sort the given array in non-decreasing order.

Note :
1. The array consists of only 3 distinct integers 0, 1, 2.
2. The array is non-empty.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of the input contains an integer T denoting the number of test cases. 

The first line of each test case contains an integer N, denoting the size of the array.

The second line of each test case contains N space-separated integers, representing the elements of the array.
Output Format :
The only line of output of each test case consists of N integers, denoting the sorted order of elements in the given array. 

Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 100
1 <= N <= 10^4
0 <= arr[i] <= 2

where arr[i] is the array element at index 'i'.

Time Limit: 1 sec
Sample Input 1 :
2
5
2 0 1 0 2
2
0 1
Sample Output 1 :
0 0 1 2 2
0 1
Explanation for Sample Input 1:
Test Case 1: After sorting the array in ascending order, we will get 0 0 1 2 2

Test Case 2: The array is already in ascending order.
Sample Input 2 :
2
6
2 1 0 0 1 2
3
0 0 0
Sample Output 2 :
0 0 1 1 2 2
0 0 0
Hint

Try to use the simplest possible approach.

Approaches (2)
Using STL

Algorithm

 

  • The simplest possible approach will be to use the in-built sort function which is available in most of programming languages.
  • So after applying the algorithm, we can simply return the array.
Time Complexity

O(N*logN), where ‘N’ is the number of elements in the array.

 

As we are sorting the given array, the time complexity is O(N*log(N))

Space Complexity

O(1) 

 

Constant extra space is required.

Code Solution
(100% EXP penalty)
Sort Array
Full screen
Console