Sollicitatievraag bij TeleTrader

Write binary search algorithm.

Antwoord op sollicitatievraag

Anoniem

12 sep 2020

Binary search is performed on sorted array. It uses the fact that array is sorted to perform in O(log n) time complexity. Idea is to look at central member of array and see how it compares to searched value. There are 3 possibilities, greater, less and equal. If it's equal we found the value. If it's greater we will continue our search in sub-array that has values greater than central member and if it's less we will continue searching sub-array that has values lesser than our central member. With this move we have divided the size of array to search in half and that is one iteration of our search. In next iteration we will do the same thing on our new sub-array that we did on our starting array: look at the value of central member and then decide is our value in left or right half or is it found. Search ends when you find value or when we get to sub-array of size of 1.