All problems

Problem 35

Sort Colors

Medium · 20 pts · Array, Two Pointers, Sorting

Problem

An array contains only the values 0, 1 and 2, standing for the colours red, white and blue. Sort it so that all the 0s come first, then all the 1s, then all the 2s, and print the result. Counting the three values and writing them back works. The classic challenge is to do it in one pass with no library sort, using the Dutch national flag algorithm: keep three pointers (low, mid, high), swap 0s to the front and 2s to the back, and leave 1s in the middle.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the sorted array, space-separated.

Constraints

1 <= N <= 100000; A[i] is 0, 1 or 2

Example input

6
2 0 2 1 1 0

Example output

0 0 1 1 2 2

Explanation

The array 2 0 2 1 1 0 has two 0s, two 1s and two 2s. Sorted, it becomes 0 0 1 1 2 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Subarray Sum Equals K Next: Spiral Matrix