Binary search is an algorithm that finds an element in a sorted list. It is much more efficient than Linear Search (3.10) because half of a list is eliminated every iteration that the value is not found.
PROCEDURE binarySearch(list, value)
{
startIndex ← 1
endIndex ← LENGTH(list)
REPEAT UNTIL(endIndex < startIndex)
{
middleIndex ← startIndex + (endIndex - startIndex) / 2
middleIndex ← middleIndex - middleIndex % 1
IF(list[middleIndex] = value)
{
RETURN(middleIndex)
}
ELSE
{
IF(list[middleIndex] > value)
{
endIndex ← middleIndex - 1
}
ELSE
{
startIndex ← middleIndex + 1
}
}
}
RETURN(-1)
}
A challenge can be found in this Khan Academy link.
Go Back