|
| 1 | +package me.ramswaroop.arrays; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by IntelliJ IDEA. |
| 7 | + * |
| 8 | + * @author: ramswaroop |
| 9 | + * @date: 8/18/15 |
| 10 | + * @time: 8:38 PM |
| 11 | + */ |
| 12 | +public class Segregate0s1sAnd2s { |
| 13 | + |
| 14 | + /** |
| 15 | + * Segregates an array {@param a} consisting of only 0s, 1s and 2s. Based on |
| 16 | + * Dutch National Flag (DNF) problem {@see: http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/}. |
| 17 | + * |
| 18 | + * @param a |
| 19 | + */ |
| 20 | + public static void segregate0s1sAnd2s(int[] a) { |
| 21 | + // assume low points to 0 and mid to 1 and high to 2 |
| 22 | + int low = 0, mid = 0, high = a.length - 1; |
| 23 | + |
| 24 | + while (mid <= high) { |
| 25 | + switch (a[mid]) { |
| 26 | + case 0: // mid points to 0 but it should point to 1 so swap it with low |
| 27 | + swap(a, low, mid); |
| 28 | + low++; |
| 29 | + mid++; |
| 30 | + break; |
| 31 | + case 1: // mid points to 1 which is correct acc. to our assumption so proceed |
| 32 | + mid++; |
| 33 | + break; |
| 34 | + case 2: // mid points to 2 instead of 1 so swap it with high |
| 35 | + swap(a, mid, high); |
| 36 | + high--; |
| 37 | + break; |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private static void swap(int[] a, int index1, int index2) { |
| 43 | + int temp = a[index1]; |
| 44 | + a[index1] = a[index2]; |
| 45 | + a[index2] = temp; |
| 46 | + } |
| 47 | + |
| 48 | + public static void main(String a[]) { |
| 49 | + int[] ar = new int[]{0, 1, 2, 0, 1, 2}; |
| 50 | + segregate0s1sAnd2s(ar); |
| 51 | + System.out.println(Arrays.toString(ar)); |
| 52 | + |
| 53 | + int[] ar1 = new int[]{0, 2, 1, 1, 2, 0}; |
| 54 | + segregate0s1sAnd2s(ar1); |
| 55 | + System.out.println(Arrays.toString(ar1)); |
| 56 | + |
| 57 | + int[] ar2 = new int[]{0, 1, 2}; |
| 58 | + segregate0s1sAnd2s(ar2); |
| 59 | + System.out.println(Arrays.toString(ar2)); |
| 60 | + |
| 61 | + int[] ar3 = new int[]{2, 1, 0, 2, 1, 0}; |
| 62 | + segregate0s1sAnd2s(ar3); |
| 63 | + System.out.println(Arrays.toString(ar3)); |
| 64 | + } |
| 65 | +} |
0 commit comments