Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm - Deepstash

Explore the World's Best Ideas

Join today and uncover 100+ curated journeys from 50+ topics. Unlock access to our mobile app with extensive features.

How Does The Binary Search Algorithm Works?

Given an array arr[] = {1, 2, 3, 5, 8, 12} and a target number k. Find the element that is just smaller than k.

Simple Solution: Linearly traverse the array and find the number that is just smaller than k. Time Complexity O(n).

Optimized Solution: Binary Search into the array.

If the middle element of the array is equal to the target, you just return the mid.

If you find the mid element bigger than the target, you just discard the mid and everything bigger than it.

If you find the mid element is smaller than the target, the mid element could be an answer, you want to keep it, but discard anything

4

12 reads

Second Idea

Given an array arr[] = {1, 2, 3, 5, 8, 12} and a target number k. Find the element that is just smaller than k.

Simple Solution: Linearly traverse the array and find the number that is just smaller than k. Time Complexity O(n).

Optimized Solution: Binary Search into the array. 

If the middle element of the array is equal to the target, you just return the mid.

If you find the mid element bigger than the target, you just discard the mid and everything bigger than it.

If you find the mid element is smaller than the target, the mid element could be an answer, you want to keep it, but discard anything

4

4 reads

IDEAS CURATED BY

CURATOR'S NOTE

You'll learn about binary search in a cool way

Other curated ideas on this topic:

Read & Learn

20x Faster

without
deepstash

with
deepstash

with

deepstash

Personalized microlearning

100+ Learning Journeys

Access to 200,000+ ideas

Access to the mobile app

Unlimited idea saving

Unlimited history

Unlimited listening to ideas

Downloading & offline access

Supercharge your mind with one idea per day

Enter your email and spend 1 minute every day to learn something new.

Email

I agree to receive email updates