Skip to content

search.binary #2

Description

@lindelwa122

Implement Binary Search Algorithm

Description

Implement the binary() method in the Search class (search.py). This method should use the binary search algorithm to find an element in a sorted list based on a custom comparator function.

Requirements

Method Signature:

@staticmethod
def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) -> Any

Parameters:

  • data: A sorted list of elements to search through
  • target: The element to find
  • comparator: A function that takes two elements and returns:
    • 0 if elements are equal
    • Negative value if first element is less than second
    • Positive value if first element is greater than second

Returns:

  • The index of the found element, OR
  • NotFoundError object (not raised, just returned) if not found

Note: The current implementation has a bug - it returns NotFoundError(...) instead of raising it. Your implementation should match this behaviour for the tests to pass.

Algorithm Details

Binary search works by:

  1. Starting with the entire sorted list
  2. Comparing the middle element with the target
  3. If equal, return the index
  4. If target is smaller, search the left half
  5. If target is larger, search the right half
  6. Repeat until found or search space is empty

Time Complexity:

  • Best case: O(1) - element is in the middle
  • Average/Worst case: O(log n)

Space Complexity: O(1) - iterative approach

Important: Binary search only works on sorted lists!

Performance Requirements

Your implementation must pass the performance test with the following criteria:

  • Dataset size: 1,000,000 elements (sorted)
  • Target position: Last element (worst case)
  • Maximum time: 0.01 seconds (10 milliseconds)
  • Binary search should be significantly faster than linear search on large datasets

Implementation Guidelines

  1. Use left and right pointers to track the search space
  2. Calculate mid point as (left + right) // 2
  3. Use the comparator to determine which direction to search
  4. Return NotFoundError object (not raise) when not found - this matches the existing bug
  5. Handle edge cases:
    • Empty lists
    • Single-element lists
    • Element not in list
    • Element smaller than all elements
    • Element larger than all elements
    • Negative numbers
    • Floats

Testing

Run the test suite to verify your implementation:

python3 -m colorful_test test_search.py

All tests related to binary() must pass, including:

  • Finding elements at various positions (first, middle, last)
  • Handling different data types (integers, floats, strings with a custom comparator)
  • Returning NotFoundError object when appropriate
  • Performance test with a huge dataset

Example Usage

from search import Search, NotFoundError

# Basic search (sorted list required!)
data = [1, 3, 5, 7, 9, 11, 13]
index = Search.binary(data, 7, lambda a, b: a - b)
print(index)  # 3

# String search with custom comparator
words = ['apple', 'banana', 'cherry', 'date']
def string_cmp(a, b):
    if a < b: return -1
    if a > b: return 1
    return 0

index = Search.binary(words, 'cherry', string_cmp)
print(index)  # 2

Comparator Function

The comparator should work like this:

def number_comparator(a, b):
    return a - b  # Negative if a < b, 0 if equal, positive if a > b

Acceptance Criteria

  • Method correctly finds elements using binary search
  • Returns the correct index of found elements
  • Raise NotFoundError object when element is not found
  • All edge cases are handled
  • Only works on sorted lists (doesn't need to verify, assumes sorted)
  • Performance test completes within 0.01 seconds for 1,000,000 elements
  • Code is clean and well-commented

Resources


Note: Do not modify the test files. Please make sure your implementation passes all existing tests. Yes, the return vs raise behaviour is unusual, but it's how the tests expect it to work!

Metadata

Metadata

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions