Tutorial 5
🎯
Binary Search
9618 A-Level
i
It may be useful to search (CTRL + F) for "binary search" questions in the (combined) past papers
If you find any bugs/edge cases in this code, please contact me
1
Binary Search
For IGCSE/O-Level/AS, you should be familiar with linear search - i.e. checking every element one by one until you find the element or until you reach the end of the array, file etc
It is important to note that for an unsorted array, linear search is the only option - it's simple, but slow, with a time-complexity of O(n) meaning that the performance degrades linearly with the number of data items - e.g. if we have an array with 100 elements, we might have to perform 100 comparisons; if we have an array with 1 trillion elements, we would have to do 1 trillion comparisons in the worst case (the item not being found)
In contrast, if and only if the array is sorted, we can use binary search - the way this works is as follows:
- Create pointers to the start, middle and end elements of the array
- If the element you are searching for is equal to the middle element, return/set a flag to true - if it's smaller, update the start and end pointers to now search the left half of the array; if it's bigger, update the pointers to search the right half of the array
- Repeat step 2 until you find the element, or return/set a flag to false if the start pointer becomes greater than the end pointer (since this means you have searched all elements and not found it)
More detailed comments can be seen in the code
Extension details/answers will be added: binary search test scores