I saw some videos about O(log n) time complexity, but then I tried a couple of binary search method on the Internet tutorial, and I am more confused now.
In computer science, big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.
An example binary search: https://jsfiddle.net/Hoyly/mhynk7gp/3/
function binarySearch(sortedArray, key){
let start = 0;
let end = sortedArray.length - 1;
while (start <= end) {
let middle = Math.floor((start + end) / 2);
console.log('count',++count,sortedArray[middle]);
if (sortedArray[middle] === key) {
return middle;
} else if (sortedArray[middle] < key) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return -1;
}
let count= 0;
console.log('first 1:');
let res1 = binarySearch([1,2,3,4,5,6,7,8],8);
console.log('first 2:');
let res2 = binarySearch([1,2,3,4,5,6,7,8],1);
console.log('answer:',res1,res2);
As you can see in the jsfiddle
The binary search here can do one extra step depending on which half of the array you are searching in. If it used Math.ceil
instead of Math.floor
then 8
would be found in three steps, while 1
would be found in four.
If we expand this to 128 items, then the last item would be found in 7 or 8 steps (again, depending on which half). In general, the real worst case for the steps taken would be log n + 1
. However, for big O, we do not consider the constants, only the growth rate of the function. O(log n + 1)
simplifies to O(log n)
. The same way how O(2n)
is still O(n)
.