Code360 powered by Coding Ninjas X Code360 powered by Coding Ninjas X
Last Updated: 17 Nov, 2020

Sort An Array of 0s, 1s and 2s

Asked in companies

Problem statement

You have been given an array/list 'arr' consisting of 'n' elements.

Each element in the array is either 0, 1 or 2.

Sort this array/list in increasing order.

Do not make a new array/list. Make changes in the given array/list.

Example :
Input: 'arr' = [2, 2, 2, 2, 0, 0, 1, 0]

Output: Final 'arr' = [0, 0, 0, 1, 2, 2, 2, 2]

Explanation: The array is sorted in increasing order.
Input Format:
The first line contains a positive integer ‘n’, which represents the length of the array/list.

The second line of each test case contains ‘n’ single space-separated integers representing the elements of the array/list.

Output Format:
The output will print ‘n’ single space-separated integers of the sorted array/list.

Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.


01 Approach

Simply, we will sort the array.