Leaderboard: add, Phase 1 — the Guard
Start with what happens on a full board. Say k = 3 and the board holds [90, 70, 50]. Someone offers 10. It is lower than everything already on the board, so it does not belong there. The board should stay exactly as it was.
That is the guard. Check it first, and return immediately if the value should not be added.
public void add(T value) {
if (size == k && value.compareTo(arr[size - 1]) <= 0) {
return; // can't beat the lowest score — doesn't make the cut
}
// ... insert and trim come next
}
- The guard only fires when
size == k. A board with room takes anything offered to it, even a new lowest score. There is no smallest score to compare against yet. arr[size - 1]is the current lowest score, becausearris sorted descending.
With the guard in place, only values that belong on the board reach the insert step.