#include "oop.h"

SortedCollection::SortedCollection(int size) : OrderedCollection(size)
{
  mSortBlock= 0;
}

oop SortedCollection::sortBlock(int (*binaryBlock)(oop x, oop y))
{
  // Make the binaryBlock define the ordering relation for the
  // elements of the receiver.
  mSortBlock= binaryBlock;
  if (notEmpty()) reSort();
  return this;
}

oop SortedCollection::addFirst(oop anObject)			{ shouldNotImplement(0); }
oop SortedCollection::addLast(oop anObject)			{ shouldNotImplement(0); }
oop SortedCollection::insertBefore(oop anObject, int index)	{ shouldNotImplement(0); }

oop SortedCollection::add(oop newObject)
{
  return OrderedCollection::insertBefore(newObject, indexForInserting(newObject));
}

int SortedCollection::indexForInserting(oop newObject)
{
  int low= mFirstIndex;
  int high= mLastIndex - 1;
  if (mSortBlock)
    while (low <= high)
      {
	int index= (high + low) / 2;
	if (mSortBlock(mArray->at(index), newObject))
	  low= index + 1;
	else
	  high= index - 1;
      }
  else
    while (low <= high)
      {
	int index= (high + low) / 2;
	if ((*mArray->at(index)) <= newObject)
	  low= index + 1;
	else
	  high= index - 1;
      }
  return low;
}

