Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Created November 11, 2015 00:03
Show Gist options
  • Save goldsborough/108596380a233d894f0b to your computer and use it in GitHub Desktop.
Save goldsborough/108596380a233d894f0b to your computer and use it in GitHub Desktop.
Finds a string in a sequence of sorted strings interspersed with empty ones.
template<typename Iterator, typename T>
bool find_with_empty(Iterator begin, Iterator end, const T& value)
{
if (begin == end || value < *begin || value > *std::prev(end))
{
return false;
}
auto middle = begin;
std::advance(middle, std::distance(begin, end)/2);
if (! middle->empty())
{
if (value < *middle)
{
return find_with_empty(begin, middle, value);
}
else if (value > *middle)
{
return find_with_empty(++middle, end, value);
}
else return true;
}
else
{
auto i = middle, j = middle;
for (auto stop = std::prev(end); i->empty() && j->empty(); )
{
if (i == begin && j == stop) return false;
if (i != begin) --i;
if (j != stop) ++j;
}
if ((! i->empty() && *i == value) ||
(! j->empty() && *j == value)) return true;
if (! i->empty())
{
if (value < *i)
{
return find_with_empty(begin, i, value);
}
else return find_with_empty(j, end, value);
}
if (! j->empty())
{
if (value > *j)
{
return find_with_empty(++j, end, value);
}
else return find_with_empty(begin, i, value);
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment