|
| 1 | +def binary_search(arr, target): |
| 2 | + """ |
| 3 | + Performs a binary search on a sorted list. |
| 4 | + Returns the index of the target if found, otherwise returns -1. |
| 5 | + """ |
| 6 | + low = 0 |
| 7 | + high = len(arr) - 1 |
| 8 | + |
| 9 | + while low <= high: |
| 10 | + # Calculate the middle index safely |
| 11 | + mid = (low + high) // 2 |
| 12 | + guess = arr[mid] |
| 13 | + |
| 14 | + # Check if the target is found at the middle position |
| 15 | + if guess == target: |
| 16 | + return mid |
| 17 | + |
| 18 | + # If the target is smaller, ignore the right half |
| 19 | + elif guess > target: |
| 20 | + high = mid - 1 |
| 21 | + |
| 22 | + # If the target is larger, ignore the left half |
| 23 | + else: |
| 24 | + low = mid + 1 |
| 25 | + |
| 26 | + # Target element is not present in the list |
| 27 | + return -1 |
| 28 | + |
| 29 | + |
| 30 | +def test_binary_search(): |
| 31 | + """ Background test cases to ensure logic accuracy before user input..""" |
| 32 | + test_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] |
| 33 | + |
| 34 | + # Test case 1: Element is in the middle |
| 35 | + assert binary_search(test_list, 23) == 5, "Test Case 1 Failed" |
| 36 | + |
| 37 | + # Test case 2: Element is at the start |
| 38 | + assert binary_search(test_list, 2) == 0, "Test Case 2 Failed" |
| 39 | + |
| 40 | + # Test case 3: Element does not exist |
| 41 | + assert binary_search(test_list, 100) == -1, "Test Case 3 Failed" |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + # For logic check |
| 46 | + test_binary_search() |
| 47 | + |
| 48 | + # --- USER INTERACTION SECTION --- |
| 49 | + print(" === Binary Search Interactive Tool === ") |
| 50 | + try: |
| 51 | + user_input = input("Enter Sorted numbers seperated by spaces (e.g.,2 5 8 12) : ") |
| 52 | + arr=[int(x) for x in user_input.split()] |
| 53 | + |
| 54 | + #check if the list is actually sorted |
| 55 | + if arr != sorted(arr): |
| 56 | + print("Error: List must be Sorted for Binary Search!") |
| 57 | + else: |
| 58 | + target = int(input("Enter The Number You Want to Find -:" )) |
| 59 | + result = binary_search(arr, target) |
| 60 | + |
| 61 | + if result != -1: |
| 62 | + print(f"Success! Element found at position : {result +1 }") |
| 63 | + print(f"Index in array : {result}") |
| 64 | + else: |
| 65 | + print("Element not found in the List.") |
| 66 | + |
| 67 | + except ValueError: |
| 68 | + print("Error: Please Enter valid integers only.") |
0 commit comments