











Segregate 0’s 1’s and 2’s in array


Sort an array of 0s, 1s, and 2s in Java
Problem statement:
Given an array arr[ ] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.
Example:
Input:
{0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}
Output:
{0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
Algorithm:
- Count the number of 0s, 1s, and 2s in the given array. Then store all the 0s in the beginning .
- Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s
- Traverse through the array and increase the count of c0 is the element is 0,increase the count of c1 is the element is 1 and increase the count of c2 is the element is 2
- Now again traverse the array and replace first c0 elements with 0, next c1 elements with 1 and next c2 elements with 2.
Java code :
import java.io.*;
class prepinsta {
static void show(int a[], int n)
{
for (int i = 0; i < n; i++)
System.out.print(a[i] + ” “);
}
// Function to sort the array of 0s, 1s and 2s
static void sortArr(int a[], int n)
{
int i, cnt0 = 0, cnt1 = 0, cnt2 = 0;
// Count the number of 0s, 1s and 2s in the array
for (i = 0; i < n; i++) {
switch (a[i]) {
case 0:
cnt0++;
break;
case 1:
cnt1++;
break;
case 2:
cnt2++;
break;
}
}
// Update the array
i = 0;
// Store all the 0s in the beginning
while (cnt0 > 0) {
a[i++] = 0;
cnt0–;
}
// Then all the 1s
while (cnt1 > 0) {
a[i++] = 1;
cnt1–;
}
// Finally all the 2s
while (cnt2 > 0) {
a[i++] = 2;
cnt2–;
}
// Print the sorted array
show(a, n);
}
// Driver code
public static void main(String[] args)
{
int a[] =
int n = a.length;
sortArr(a, n);
}
}
Output :
array after segregation
0 0 0 0 0 1 1 1 1 1 2 2
Can’t we use Arrays.sort(arr)
where arr is input arr given by user