Sorting In Linear Time [codingblocks]

You will be given an array containing only 0s, 1s and 2s. you have sort the array in linear time that is O(N) where N is the size of the array.


Input Format
The first line contains N, which is the size of the array. The following N lines contain either 0, or 1, or 2.

Constraints
1 <= N <= 10^6
Each input element x, such that x ∈ { 0, 1, 2 }.

Output Format
Output the sorted array with each element separated by a newline.

Sample Input
5
0
1
2
1
2

Sample Output
0
1
1
2
2


Java Code:



/*
Amit Kumar
06-12-2020
IDE Code: https://ide.geeksforgeeks.org/sMPEca9iga
*/

package array;
import java.util.Scanner;

public class Array_SortingInLinearTime {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int count = scanner.nextInt();
        int[] arr = new int[count];
        for (int i=0; i<count; i++) {
            arr[i] = scanner.nextInt();
        }

        int zero, one, two;
        zero=0; one=0; two=0;

        for (Integer value : arr) {
            if (value == 0) zero++;
            else if (value == 1) one++;
            else two++;
        }

        int index=0;
        while (zero-- > 0){
            arr[index++] = 0;
        }
        while (one-- > 0){
            arr[index++] = 1;
        }
        while (two-- > 0){
            arr[index++] = 2;
        }

        for (Integer value : arr) {
            System.out.println(value);
        }
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )