Binary search Algorithm - Python

Sasikala

In python, while implementing the binary search algorithm, which math function is optimal to be used to find out the mid value - floor or ceil ?

shivam mitra

You don't need to use either ceil or floor function for implementing binary search in python. Depending on the problem, you have to round the mid value up or down.

 mid = low + (high-low)/2 #rounds down the mid value
 mid = low + (high-low+1)/2 #rounds up the mid value

Try to solve these two problems, you will get an idea how this works.

  1. Given an array A and a target value, return the index of the first element in A equal to or greater than the target value
  2. Given an array A and a target value, return the index of last element which is smaller than target value.

First try these problems on your own and if you get stuck, refer to the this.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Unexpected behavior of binary search algorithm in python

From Dev

Randomized binary search algorithm

From Dev

Binary Search algorithm implementations

From Dev

Binary search the answer algorithm

From Dev

Binary Search Tree? Algorithm

From Dev

Binary Search algorithm implementations

From Dev

Binary Search Algorithm is not working

From Dev

Binary Search Tree Algorithm Sequence

From Dev

Making use of binary search algorithm

From Dev

Problem with implementing the binary search algorithm

From Dev

Does this mean binary search algorithm?

From Dev

Execution time for successful search Binary Search algorithm

From Dev

Python binary multiplication algorithm?

From Dev

python implicit binary search

From Dev

Binary Search python 3.5

From Dev

python implicit binary search

From Dev

Recursive binary search in Python

From Dev

Binary search function python

From Dev

Python Hashing binary search

From Dev

Khan academy Algorithm: Binary Search Solution

From Dev

How to use recursion in creating a binary search algorithm

From Dev

How to call upon a Binary Search Tree in an algorithm

From Dev

java.lang.StackOverflowError in Binary Search Algorithm

From Dev

What is the Sherwood binary search algorithm in Java?

From Dev

Golang Binary Search Tree Algorithm Translation

From Dev

What is wrong with my Binary Search algorithm implementation?

From Dev

Segmentation fault in recursive Binary Search Algorithm in C

From Dev

What is wrong with my Binary Search algorithm implementation?

From Dev

Could this recursive binary search algorithm be more efficient?