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

--

--

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