WRITELOOP

GROKKING ALGORITHMS - BINARY SEARCH

2022 April 5
  • What is binary search? Binary search is an algorithm that can be used when you need to find an element with the less iterations possible. Given e.g. a list of 100 elements, you start your search at the middle position (50). Then, if the element is not that, you keep dividing your list in half until you find the desired element.

  • What is the pre-requisite to use the binary search algorithm? Your list of elements must be already sorted in ascendent order (from the smallest to the greatest).

  • What is logarithmic time - regarding the time to run an algorithm? That means that for a list with n elements, you will need log2 n steps on the worst scenario.

  • What is linear time - regarding the time to run an algorithm? That means that for a list with n elements, you will go through all the list from the 1st element to the last, needing n steps in the worst scenario (on which the element is on the last position of the list).

  • What is a logarithm? They are the flip of exponentials. E.g.:

###
 3
2  = 8         == 	log 8 = 3
###
 4
2  = 16        == 	log 16 = 4
                           2
###
 5
2  = 32        == 	log 32 = 5
```                          2

- Suppose you have a sorted list of 128 names and you're searching using binary search. What's the maximum number of steps it would take?
7 steps. (see why below)

x 2 = 128, so x = 7

2 4 8 16 32 64 128 256 (numbers) …………………. 1 2 3 4 5 6 7 8 (index)


- Suppose you have a sorted list of 256 names and you're searchin using binary search. What's the maximum number of steps it would take?
8 steps. (see why below)

x 2 = 256, so x = 8

2 4 8 16 32 64 128 256 …………………. 1 2 3 4 5 6 7 8

---