irborrero
8/5/2019 - 4:41 PM

Heaps - min max to sort


Heap smallerScores = new PriorityQueue<Integer>();
Heap greaterScores = new PriorityQueue<Integer>(); // TODO Comparable to create a minHeap

  int getMedian() {
    if (smallerScores.size() == greaterScores.size()) {
      return (smallerScores.peek() + greaterScores.peek()) / 2 ;
    } else {
      if (smallerScores.size() > greaterScores.size()) {
        return smallerScores.peek();
      } else {
        return greaterScores.peek();
      }
    }
  }

  void addScore(int score) {
    if (score > smallerScores.peek()) {
      greaterScores.push(score);
    } else {
      smallerScores.push(score);
    }
      if (Math.abs(smallerScores.size() - greaterScores.size()) > 1) {
      balance();
    }
}

private void balance() {
  if (smallerScores.size() > greaterScores.size()) {
    greaterScores.push(smallerScores.remove());
  } else {
    smallerScores.push(greaterScores.remove());
  }
}