forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsamplebinarysearch.py
More file actions
54 lines (45 loc) · 1.32 KB
/
samplebinarysearch.py
File metadata and controls
54 lines (45 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File: Programs/samplebinarysearch.py
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'Lib'))
import flexsearch
def main():
while True:
# User input
numbers = input("\nEnter numbers separated by space or comma (or '-1' to quit): ").strip()
if numbers.lower() == '-1':
break
if not numbers:
print("No numbers entered. Try again.")
continue
mode = input("Enter sort mode (a/d/min/max): ").strip().lower()
if mode not in ('a', 'd', 'min', 'max'):
print("Invalid sort mode. Try again.")
continue
target_str = input("Enter target number for search: ").strip()
try:
target = int(target_str)
except ValueError:
print("Invalid target number. Try again.")
continue
# Parse numbers safely
try:
arr = flexsearch.parse_numbers(numbers)
if not arr:
print("No valid numbers found. Try again.")
continue
except ValueError:
print("Invalid number format. Try again.")
continue
# Sort and search
sorted_arr = flexsearch.sort_numbers(arr, mode)
idx = flexsearch.binary_search(sorted_arr, target)
# Output results
print("\nInput string:", numbers)
print("Sorted array:", sorted_arr)
if idx == -1:
print(f"Target {target} not found in the array.")
else:
print(f"Target {target} found at index:", idx)
if __name__ == "__main__":
main()