Classic algorithms · 9 / 22 Exercise Medium

Binary search

Objective

Create a Python program that looks for a number in a sorted list using binary search and counts how many steps it needs.

Instructions

  • Read a line with integers sorted from smallest to largest and, on the next line, the number to look for.
  • Use two indexes left = 0 and right = len(list) - 1. While left <= right: add 1 to the steps, compute middle = (left + right) // 2 and compare. If it is the target, finish; if the middle element is smaller, do left = middle + 1; if it is larger, right = middle - 1.
  • Show Position: P on the first line (or Not found if it is not there) and Steps: K on the second.
Input
1 3 5 7 9 11 13
11
Output
Position: 5
Steps: 2

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise