The function receives an array and an item. The function orders the array and if the item is in the array, the function returns its position.
Position number ...
// JAVASCRIPT
function BinarySearch(aList, Item) {
aList.sort( (a,b)=>a-b );
var lowPos = 0;
var highPos = aList.length - 1;
var middlePos;
var guess;
var result = 'Null';
// repeat while it has not yet arrived at a single element
while(lowPos<=highPos) {
middlePos = Math.round( (lowPos + highPos) / 2 );
guess = aList[middlePos];
if(guess == Item) {
result = middlePos;
}
if(guess > Item) {
highPos = middlePos - 1;
}
else {
lowPos = middlePos + 1;
}
}
return result;
}
// PYTHON
def BinarySearch(aList, Item):
lowPos = 0
highPos = len(aList) - 1
while lowPos<=highPos:
middlePos = (lowPos+highPos)/2
guess = aList[middlePos]
if guess == Item:
return middlePos
if guess > Item:
highPos = middlePos - 1
else:
lowPos = middlePos + 1
return None
# Test
my_list = [1,3,5,7,9]
print BinarySearch(my_list, 3) #=> 1
print BinarySearch(my_list, -1) #=> None