// Sorted buffer implementation.

#include "sorted_buffer.h"

// This overrides buffer::add.
// Add new item to buffer in its correct sorted position.
// We do this by adding it to the end of the queue and then
// scanning backwards for the correct position.
// (A technique very similar to the insertion sort algorithm.)
// Note that if the buffer is full we silently ignore the request.
void sorted_buffer::add(int x)
{
  if (!isfull())
  {
    int i = tail;
    while (i != head)
    {
      int j = i;
      decrement(j);
      if (buf[j] < x)
        break;
      buf[i] = buf[j];
      i = j;
    }
    buf[i] = x;
    increment(tail);
  }
}

// Decrement an index in the buffer modulo its length
// (i.e., "wrapping around" the begining of the array back to the end).
void sorted_buffer::decrement(int & i) 
{       
  if (i == 0)
    i = last;
  else
    --i;
}
