DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Amira Abdelhalim
Amira Abdelhalim

Posted on

Binary Search vs Simple Search

I have been reading Gorkking Algorithms by Aditya Y.Bhargava. The book is one of the most interesting and enjoyable books about algorithms, so I thought I would share insights from each chapter.

Chapter one is mainly about the differences between simple search and binary search, the differences are as follow:

  β€œstudy case searching for number 10 in a list of 10 elements”

β€’ simple search would loop on each element check if it is number 10 in case number 10 is the last element we would loop 10 times to reach our element …. what is the list is 1000,000 elements?

β€’ Binary search is one of the searching algorithms that requires a sorted list as an input and outputs the location of the required element or null if doesn’t exist.

β€’ Binary search works as follow => β€œwe are still working on our 10 elements list”
1. Low => 0   first element of the list
2. high => length(list) – 1  the last element of the list
3. mid => (low + high) / 2
β€’ check if number 10 is equal to mid if yes … Congratulations number 10 is found
β€’ if number 10 is greater than mid … update low value to mid and recalculate mid value
β€’ if number 10 is less than mid update high value to mid and recalculate mid value 
  β€œIN THIS STEP WE ELIMINATED THE LIST BY HALF”
β€’ Repeat the past two steps until 10 is found.

β€’ binary search would find an element in a list of 10 elements in only 3 steps if the element is the last element… if it is a list of 1000,000 elements it would take 20 steps only.

β€’ simple search complexity according to big O notation is O(n).

β€’ binary search complexity is O(log n).
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.