Step by step animation. For the programming beginners to get a better understanding of binary search.(Click snail button to start animation and click it again to go back to the first page)
Search a keyword, if found, return the index of the item in the array, if not found, return the index where the element should be inserted.(4 example keywords)
Cost: O(logn)
Binary search code in C++:
Search a keyword, if found, return the index of the item in the array, if not found, return the index where the element should be inserted.(4 example keywords)
Cost: O(logn)
Binary search code in C++:
int binsearch( vector<string> words, int low, int high, string word )
{
if ( high < low ) return -low ;//position to insert
int mid = (low+high) / 2;
if(words[mid]==word)
{
return mid;
}
else if ( word < words[mid] )
{
return binsearch( words, low, mid-1, word );
}
else
{
return binsearch( words, mid+1, high, word );
}
No comments:
Post a Comment