How to Sort an Array of 0s, 1s, and 2s in Java

Sort an array of 0s, 1s, and 2s in Java

Examples

Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2}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}

Index

  1. The Brute Force Approach
  2. The Counting Approach
  3. The Three Pointer Approach — Dutch National Flag Approach

The Brute Force Approach

Algorithm

  1. Use two loops for i and j=i+1 elements
  2. Compare them to see if the ith element is bigger than the jth element
  3. If yes, swap their position so that the smaller element comes first as we have to arrange the elements in ascending order.
  4. Print the array

Psuedo Code

for(i=0 -> N){for(j=i+1 -> N){if(A[i] > A[j]){Swap(A[i], A[j])}}}Print A

Output

--

--

--

I am a front-end developer from India with over one year of experience in freelancing with skills like Git, HTML5, CSS3, Bootstrap 4&5, and React.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Understanding Pods — Kubernetes

Optimized permanent minimization in MySQL 8.0

Optimized permanent minimization in MySQL 8.0

Creating Complex Automation Using IFTTT and Stringify

10 Headless CMS Options

Devenings

Implementing Night Mode

Night node demonstration

What is Java and why you need to learn it? Explanation for beginners ))

Using Arduino board as ISP to program ATmega328 IC without a crystal

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ateev Duggal

Ateev Duggal

I am a front-end developer from India with over one year of experience in freelancing with skills like Git, HTML5, CSS3, Bootstrap 4&5, and React.

More from Medium

Java String is immutable — What does it actually mean?

Multithreading In Java

OOPs and Exception Handling in Java

The optimal approach to find the nth Fibonacci number using recursion in Java