Skip to content
Exercises · Q4

Q.Write a program that takes as input a list of 10 integers and a key value and applies binary search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different key values and note the results.

Uttar Pradesh UpmspTextbookSubjective· 3mImportance★★★★★
65% · 11/17 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Implement binary search on a sorted list of 10 integers to find a key's position, with three test runs demonstrating found and not-found cases.

Binary search is the right tool here because it efficiently locates an element in a sorted list by repeatedly halving the search space. Instead of checking every element (linear search, O(n)O(n)), binary search compares the key with the middle element and eliminates half the remaining elements in each step, achieving O(log⁡n)O(\log n) time complexity.

The algorithm works only on sorted data. If the middle element matches the key, we're done. If the key is smaller, we search the left half; if larger, the right half. We repeat until we find the key or exhaust the search space.

The Algorithm

  1. Sort the list (binary search requires sorted input).
  2. Set low = 0 and high = len(list) - 1.
  3. While low ≤ high:
    • Calculate mid = (low + high) // 2.
    • If list[mid] == key, return mid.
    • If key < list[mid], set high = mid - 1 (search left half).
    • If key > list[mid], set low = mid + 1 (search right half).
  4. If the loop exits, the key is not present.
Watch out

Binary search only works on sorted lists. If you apply it to an unsorted list, the result is unpredictable. Always sort first or verify the list is already sorted.

Complete Python Program

def binary_search(arr, key):
    """
    Performs binary search on a sorted list.
    Returns the index if key is found, otherwise -1.
    """
    low = 0
    high = len(arr) - 1
    
    while low <= high:
        mid = (low + high) // 2
        
        if arr[mid] == key:
            return mid  # Key found at index mid
        elif key < arr[mid]:
            high = mid - 1  # Search in left half
        else:
            low = mid + 1   # Search in right half
    
    return -1  # Key not found


# Main program
numbers = []
print("Enter 10 integers:")
for i in range(10):
    num = int(input(f"Enter number {i+1}: "))
    numbers.append(num)

# Sort the list (required for binary search)
numbers.sort()
print(f"\nSorted list: {numbers}")

# Test with 3 different key values
test_keys = []
print("\nEnter 3 key values to search:")
for i in range(3):
    key = int(input(f"Enter key {i+1}: "))
    test_keys.append(key)

print("\n" + "="*50)
print("SEARCH RESULTS")
print("="*50)

for key in test_keys:
    result = binary_search(numbers, key)
    
    if result != -1:
        print(f"\nKey {key}: FOUND at position {result} (0-indexed) or position {result+1} (1-indexed)")
    else:
        print(f"\nKey {key}: NOT FOUND in the list")

Sample Run with Three Test Cases

Input:

Enter 10 integers:
Enter number 1: 45
Enter number 2: 12
Enter number 3: 78
Enter number 4: 23
Enter number 5: 56
Enter number 6: 89
Enter number 7: 34
Enter number 8: 67
Enter number 9: 90
Enter number 10: 11

Sorted list: [11, 12, 23, 34, 45, 56, 67, 78, 89, 90]

Enter 3 key values to search:
Enter key 1: 56
Enter key 2: 100
Enter key 3: 11

Output:

==================================================
SEARCH RESULTS
==================================================

Key 56: FOUND at position 5 (0-indexed) or position 6 (1-indexed) …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.