Binary Search:

This is out Online Judge Demo. Try out our online judge.

In computer science, binary search is a search algorithm that finds the position of a target value within a sorted array.

Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.

Example:

Input:

arr = [1, 2, 4], target = 2

Output:

1

Explanation:

Return the index of the target value.

Example:

Input:

arr = [1, 2, 4], target = 0

Output:

-1

Explanation:

Return -1 if the target value not exist in the array.

This is out Online Judge Demo. Try out our online judge.

In computer science, binary search is a search algorithm that finds the position of a target value within a sorted array.

Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.

Example:

Input:

arr = [1, 2, 4], target = 2

Output:

1

Explanation:

Return the index of the target value.

Example:

Input:

arr = [1, 2, 4], target = 0

Output:

-1

Explanation:

Return -1 if the target value not exist in the array.

def binary_search(array, target):

Learn from Facebook, Google, Uber senior engineers interviewed 100+ candidates.aonecode.com

Most recent interview questions and system design topics gathered from aonecode alumnus.

One-to-one online classes. Get feedbacks from real interviewers.

Already a coding expert? - Advance straight to hard interview topics of your interest.

New to the ground? - Develop basic coding skills with your own designated mentor.

Days before
interview? - Focus on most important problems in target company question bank.