Given an array consisting of 0
s, 1
s and 2
s, sort the array.
Solve the problem in linear time.
Example 1:
arr=[0, 1, 2, 0, 0, 1, 2, 1, 2]
[0, 0, 0, 1, 1, 1, 2, 2, 2]
Example 2:
arr=[0, 2, 1, 0]
[0, 0, 1, 2]
One of the easiest solutions to this problem is to count the number of zeros, ones, and twos. Replace the elements of the array with the number of zeros, ones, and twos.
The steps of the algorithms are as follows:
counter_zero
.counter_one
.counter_two
.counter_zero
elements with 0, then the next counter_one
elements with 1, and finally the next counter_two
elements with 2.Time Complexity: O(n)
Space Complexity: O(1)
The downside of this approach is the array is traversed twice. Refer to The Dutch national flag problem in C++ for an optimized approach.
Let’s look at the code below:
import java.util.Arrays;class Main{public static void sort(int[] arr) {int counter_zero = 0;int counter_one = 0;int counter_two = 0;for(int element:arr)switch (element){case 0: counter_zero++;break;case 1: counter_one++;break;case 2: counter_two++;break;default:System.out.println("Unknown number");return;}for (int i = 0; i < counter_zero; i++)arr[i] = 0;for (int i = counter_zero; i < (counter_zero + counter_one); i++)arr[i] = 1;for (int i = (counter_zero + counter_one); i < (counter_zero + counter_one + counter_two); i++)arr[i] = 2;}public static void main(String[] args) {int[] arr = { 0, 1, 2, 0, 0, 1, 2, 1, 2};System.out.println("Original Array - " + Arrays.toString(arr));sort(arr);System.out.println("Sorted Array - " + Arrays.toString(arr));}}
counter_zero
.counter_one
.counter_two
.counter_zero
number of times.counter_one
number of times.counter_two
number of times.arr
is defined.sort()
method is called to sort arr
.