Sort 0 1 2

 

You are given an integer array/list(ARR) of size N. It contains only 0s, 1s and 2s. Write a solution to sort this array/list in a 'single scan'.

'Single Scan' refers to iterating over the array/list just once or to put it in other words, you will be visiting each element in the array/list just once.


Sample Input 1:
7
0 1 2 0 2 0 1
Sample Output 1:
0 0 0 1 1 2 2

import java.util.Scanner;

public class Sort012 {

	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		int n=s.nextInt();
		int a[]=new int[n];
		for(int i=0;i<n;i++)
		{
			a[i]=s.nextInt();
		}
		
		sort012(a);
		print(a);

	}
	
	public static void print(int a[])
	{
		System.out.println("Updated Array -> ");
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+" ");
		}

	}
	public static void sort012(int[] arr){

		int l=arr.length;
		int zero=0;
		int one=0;

		for(int i=0;i<l;i++)
		{
			if(arr[i]==0)
			{
				zero++;
			}
			else if(arr[i]==1)
			{
				one++;
			}
		}
		for(int i=0;i<zero;i++)
		{
			arr[i]=0;
		}
		for(int i=zero;i<one+zero;i++)
		{
			arr[i]=1;
		}
		for(int i=one+zero;i<l;i++)
		{
			arr[i]=2;
		}
		
}
}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern