{"record":{"id":"89cc16da8b4e2f2e","repo":"TheAlgorithms/Python","slug":"sorted-collection-must-be-sorted-in-ascending-orde","errorCode":null,"errorMessage":"sorted_collection must be sorted in ascending order","messagePattern":"sorted_collection must be sorted in ascending order","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"searches/binary_search.py","lineNumber":201,"sourceCode":"    Be careful collection must be ascending sorted otherwise, the result will be\n    unpredictable\n\n    :param sorted_collection: some ascending sorted collection with comparable items\n    :param item: item value to search\n    :return: index of the found item or -1 if the item is not found\n\n    Examples:\n    >>> binary_search([0, 5, 7, 10, 15], 0)\n    0\n    >>> binary_search([0, 5, 7, 10, 15], 15)\n    4\n    >>> binary_search([0, 5, 7, 10, 15], 5)\n    1\n    >>> binary_search([0, 5, 7, 10, 15], 6)\n    -1\n    \"\"\"\n    if any(a > b for a, b in pairwise(sorted_collection)):\n        raise ValueError(\"sorted_collection must be sorted in ascending order\")\n    left = 0\n    right = len(sorted_collection) - 1\n\n    while left <= right:\n        midpoint = left + (right - left) // 2\n        current_item = sorted_collection[midpoint]\n        if current_item == item:\n            return midpoint\n        elif item < current_item:\n            right = midpoint - 1\n        else:\n            left = midpoint + 1\n    return -1\n\n\ndef binary_search_std_lib(sorted_collection: list[int], item: int) -> int:\n    \"\"\"Pure implementation of a binary search algorithm in Python using stdlib\n","sourceCodeStart":183,"sourceCodeEnd":219,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/searches/binary_search.py#L183-L219","documentation":"Raised by binary_search in searches/binary_search.py when the input list is not in non-decreasing ascending order. Binary search's O(log n) correctness depends entirely on the precondition that the collection is sorted, so the function defensively checks every adjacent pair with itertools.pairwise and rejects the input up front rather than silently returning a wrong index. If you see this error, the list you passed has at least one element greater than its successor.","triggerScenarios":"binary_search([10, 5, 7, 10, 15], 5); passing a list sorted with sort(reverse=True); passing a list after appending a smaller element to an already-sorted list; binary_search(list(d.keys()), item) where keys were never sorted.","commonSituations":"Forgetting to call sorted() before searching; mixing ascending and descending data from an API; reusing a list that an earlier code path sorted differently; assuming database or CSV rows arrive sorted when they do not.","solutions":["Sort the collection before searching: binary_search(sorted_collection := sorted(data), item).","If duplicates exist, remember non-decreasing order is fine ([1,2,2,3] passes); only actual inversions fail.","If you must search unsorted data, use a linear search (e.g. searches/linear_search.py) or index.find on a sorted copy.","Keep data sorted at insertion time so the precondition holds by construction."],"exampleFix":"# before\nidx = binary_search(data, 42)  # data = [15, 10, 7, 5, 0]\n\n# after\ndata = sorted(data)\nidx = binary_search(data, 42)","handlingStrategy":"validation","validationCode":"from itertools import pairwise\n\ndef is_ascending(lst):\n    return all(a <= b for a, b in pairwise(lst))\n\nassert is_ascending(data), 'data must be sorted before binary_search'","typeGuard":"def is_sorted_list(lst: list) -> bool:\n    return isinstance(lst, list) and all(a <= b for a, b in zip(lst, lst[1:]))","tryCatchPattern":"try:\n    idx = binary_search(data, item)\nexcept ValueError:\n    data = sorted(data)\n    idx = binary_search(data, item)","preventionTips":["Sort once, search many times: keep a canonical sorted copy of the dataset.","Non-decreasing order is legal; duplicates do not trigger the error.","Add an assertion in tests that fixtures passed to binary search are sorted."],"tags":["search","binary-search","precondition","sorted-input"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}