wavec022

binary search

Apr 1st, 2020
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. Binary Search
  2.  
  3. Linear Search
  4. Array(11,23,8, etc etc)
  5. Linear time
  6.  
  7. Big idea: divide and conquer, reduce search area by half each time
  8. but only if array is sorted
  9.  
  10. Pseudocode
  11. Repeat following steps until sub array is of size 0
  12. Calculate midpoint of current array
  13.  
  14. If target at middle, stop
  15. Else if target < middle, repeat but change endpoint to be just left of middle
  16. Else if target > middle, repeat but change start point to be just right of middle
  17.  
  18. ==========
  19.  
  20. Example:
  21.  
  22. Array(11, 23, 8, 14, 30, 9, 6, 17, 22, 28, 25, 15, 7, 10, 19)
  23. Sort it
  24. Array(6,7,8,9,10,11,14,15,17,19,22,23,25,28,30)
  25.  
  26. Target = 19
  27. Start = 0
  28. End = 14
  29. Middle = 7 ((end + start)/2)
  30.  
  31. Is 15 (index 7) what we are looking for? No. Target > 15 so we move right; the new start point is 8
  32. 8 + 14 = 22/2 = 11 (new middle)
  33.  
  34. Is 23 (index 11) what we want? No. Target < 23 so we move left; new end point is 10
  35. New middle is 9
  36. Is 19 what we want? Yes!
  37.  
  38. ===========
  39.  
  40. If we don't find the element (because it's not in the array) then the start and end will be the same and that one element will still not be the right one
Add Comment
Please, Sign In to add comment