package median;

public class MedianTest {
  public static void main(String[] args) {
    double[] a1 = {1, 3, 8, 20, 28, 50, 100};
    double[] a2 = {20, 101, 28, 8, 50, 3, 100, 1};
    double[] a3 = {20, 101, 23, 28, 23, 8, 50, 3, 100, 1};
    // want these to be true
    System.out.println(testMedian(20, a1));
    System.out.println(testMedian(24, a2));
    System.out.println(testMedian(23, a3));
    // want these to be false
    System.out.println(testMedian(8, a1));
    System.out.println(testMedian(25, a2));
    System.out.println(testMedian(28, a2));
    System.out.println(testMedian(24, a3));
  }

  public static boolean testMedian(double x, double[] a) {
    // used for counting how many numbers in the array a
    // are smaller, equal, or bigger than x
    int countSmaller = 0;
    int countEqual = 0;
    int countBigger = 0;
    // keep track of the largest number less than x
    double maxLessThanX = Double.MIN_VALUE;
    // keep track of the smallest number greater than x
    double minGreaterThanX = Double.MAX_VALUE;
    for (int i = 0; i < a.length; i++) {
      if (a[i] < x) {
        countSmaller++;
        if (maxLessThanX < a[i]) maxLessThanX = a[i];
      }
      else if (a[i] > x) {
        countBigger++;
        if (minGreaterThanX > a[i]) minGreaterThanX = a[i];
      }
      else countEqual++;
    }
    System.out.println("counts are " + countSmaller + ", "
                       + countEqual + ", " + countBigger);
    System.out.println(x + " is greater than " + maxLessThanX
                       + " and is less than " + minGreaterThanX );
    // I've changed the logic to identify when to return true
    double half = (double) a.length / 2;
    if (countSmaller < half && countBigger < half) return true;
    if (countSmaller == half && countBigger == half) {
      double avg = (maxLessThanX + minGreaterThanX) / 2.0;
      // accept any value close to avg (see p. 221 in book)
      if (Math.abs(x - avg) < 0.0001) return true;
    }
    return false;
  }
}




