/* An instance of this class can partition arrays in accord with a ** RED/BLUE classifier provided at construction. ** Author: R. McCloskey and ... */ public class RedBluePartitioner { // instance variable // ----------------- // to distinguish RED values from BLUE values protected RedBlueClassifier rbClassifier; // constructor // ----------- /* Establishes the given RedBlueClassifier as that to be used by ** this object in partitioning arrays. */ public RedBluePartitioner(RedBlueClassifier classifier) { this.rbClassifier = classifier; } // method of interest // ------------------ /* Rearranges the elements of the given array b[] so that, for some k ** satisfying 0 <= k <= b.length, all RED elements are in b[0..k) ** and all BLUE elements are in b[k..b.length). The value returned ** is k. */ public int partition(T[] b) { int k = 0, m = b.length; // loop invariant: 0 <= k <= m <= b.length && // all elements in b[0..k) are RED && // all elements in b[m..b.length) are BLUE while (k != m) { if (b[k] is RED) { k++; } else if (b[m-1] is BLUE) { m--; } else { // b[k] is BLUE and b[m-1] is RED swap(b, k, m-1); k++; m--; } } return k; } // private utility // --------------- /* Swaps the elements at the specified locations of the specified array. */ private static void swap(Object[] a, int p, int q) { Object temp = a[p]; a[p] = a[q]; a[q] = temp; } }