In this program, we are going to share a Java program to sort an array of 0, 1 and 2. If you are a Java beginner and want to start learning the Java programming, then keep your close attention in this tutorial as I am going to share how to write a Java program to sort an array of 0, 1 and 2.
Copy the below Java program and execute it with the help of Javac compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import java.io.*; class countzot { // Sort the input array, the array is assumed to // have values in {0, 1, 2} static void sort012(int a[], int arr_size) { int lo = 0; int hi = arr_size - 1; int mid = 0,temp=0; while (mid <= hi) { switch (a[mid]) { case 0: { temp = a[lo]; a[lo] = a[mid]; a[mid] = temp; lo++; mid++; break; } case 1: mid++; break; case 2: { temp = a[mid]; a[mid] = a[hi]; a[hi] = temp; hi--; break; } } } } /* Utility function to print array arr[] */ static void printArray(int arr[], int arr_size) { int i; for (i = 0; i < arr_size; i++) System.out.print(arr[i]+" "); System.out.println(""); } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}; int arr_size = arr.length; sort012(arr, arr_size); System.out.println("Array after seggregation "); printArray(arr, arr_size); } } |
array after segregation 0 0 0 0 0 1 1 1 1 1 2 2
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.