Binary search

Learn Algorithms · 4:48

Listen on 93

Lyrics

[Verse 1]
Got a sorted list, million items long
Need to find that value, but the search feels wrong
Linear scan would take forever, ain't nobody got time
Binary search is the answer, algorithmic shine
Start with left and right pointers, mark the boundary
Middle index is our target, mathematical harmony
If the middle's what we're seeking, then we celebrate
If it's less we go left side, if it's more we navigate

[Chorus]
Cut it in half, cut it in half
Logarithmic time is the optimal path
Divide and conquer, that's the way
O of log n every single day
Cut it in half, cut it in half
Binary search is our algorithmic staff
Left or right, never both sides
Efficiency is our programming guide

[Verse 2]
Precondition check the data, sorted is the key
Random order won't work here, that's the guarantee
Low equals zero starting point, high equals length minus one
While low is less than or equal high, the algorithm runs
Calculate the middle value, low plus high divided two
Integer division keeps us clean, no floating point to skew
Compare the target with middle, three outcomes we can see
Equal means we found it, less or greater guides our spree

[Chorus]
Cut it in half, cut it in half
Logarithmic time is the optimal path
Divide and conquer, that's the way
O of log n every single day
Cut it in half, cut it in half
Binary search is our algorithmic staff
Left or right, never both sides
Efficiency is our programming guide

[Bridge]
When target's less than middle value
Move the right pointer down
High equals middle minus one now
Search space has been crowned
When target's more than middle value
Move the left pointer up
Low equals middle plus one
Fill efficiency's cup

[Verse 3]
Worst case scenario analysis, how many steps we take
Log base two of n comparisons, that's the performance break
Million items needs just twenty, billion needs just thirty
Linear search would kill your runtime, binary keeps it dirty
Return the index when we find it, negative one when not
Base case handles empty arrays, edge cases on the spot
Iterative or recursive style, both approaches work the same
Binary search mastery earned you algorithmic fame

[Chorus]
Cut it in half, cut it in half
Logarithmic time is the optimal path
Divide and conquer, that's the way
O of log n every single day
Cut it in half, cut it in half
Binary search is our algorithmic staff
Left or right, never both sides
Efficiency is our programming guide

[Outro]
Sorted data, binary search
Logarithmic time research
Half the space with every step
Algorithm mastery rep

← Counting sort | Linear search →