Skip to content

Commit 359abbd

Browse files
Merge pull request steam-bell-92#290 from Ishita-varshney/feature-search-sort
Implement core interactive Binary search and Bubble Sort algorithms
2 parents 9b6b61c + 6991a85 commit 359abbd

2 files changed

Lines changed: 112 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
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.")

math/Bubble-Sort/bubble_sort.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def bubble_sort(arr):
2+
"""
3+
Sorts a list in-place using the Bubble Sort algorithm.
4+
Returns the sorted list.
5+
"""
6+
n = len(arr)
7+
for i in range(n):
8+
swapped = False
9+
# Last i elements are already in place
10+
for j in range(0, n-i-1):
11+
# Swap if the element found is greater than the next element
12+
if arr[j] > arr[j+1]:
13+
arr[j],arr[j+1]=arr[j+1],arr[j]
14+
swapped = True
15+
# If no two elements were swapped by inner loop , then break
16+
if not swapped:
17+
break
18+
return arr
19+
20+
def test_bubble_sort():
21+
"""Background test cases to ensure logic accuracy before user input."""
22+
assert bubble_sort([64, 34, 25, 12, 22, 11, 90]) == [11, 12, 22, 25, 34, 64, 90]
23+
assert bubble_sort([5, 1, 4, 2, 8]) == [1, 2, 4, 5, 8]
24+
25+
if __name__ == "__main__":
26+
#Background testing execution
27+
test_bubble_sort()
28+
29+
# --- USER INTERACTION SECTION ---
30+
print("=== Bubble Sort Interactive Tool ===")
31+
try:
32+
user_input = input("Enter numbers to sort seperated by spaces (e.g., 64 34 25) :")
33+
if not user_input.strip():
34+
print("Error: Input cannot be empty!")
35+
else:
36+
# Convert String Input into List of Integers
37+
arr=[int(x) for x in user_input.split()]
38+
print(f"Original list : {arr}")
39+
40+
# Sort operation performed
41+
sorted_arr = bubble_sort(arr)
42+
print(f"Sorted list: {sorted_arr}")
43+
except ValueError:
44+
print("Error: Please enter valid integers only.")

0 commit comments

Comments
 (0)