I have an array containing names of items. I want to give the user the option to create items without specifying their name, so my program will have to supply a unique defau
A logarithmic-time approach, assuming that you never leave "holes" by deleting items:
// Inverse binary search for the last one.
int upperBound = 1;
while(isInUse(upperBound)) upperBound *= 2;
// Standard binary search for the end once we have a ballpark.
int lowerBound = upperBound / 2;
while(lowerBound < upperBound - 1)
{
int midpoint = (lowerBound + upperBound) / 2;
if (isInUse(midpoint))
lowerBound = midpoint;
else
upperBound = midpoint;
}
return upperBound;
If item numbers can be freed by deleting, nothing short of linear search will work unless you also keep a "free list" and pick from that.