B.Sc Computer Science with Data Analytics
Python Programming - Lab
Core Lab 5
Bharathiar University
Program 12 - Write a python program for Linear Search and Binary Search.
SOURCE CODE:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the target element if found
return -1 # Return -1 if the target element is not in the list
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Return the index of the target element if found
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1 # Return -1 if the target element is not in the list
# Main program
arr_input = input("Enter the elements of the array separated by space: ")
arr = list(map(int, arr_input.split()))
print("Entered Array:", arr)
search_method = input("Choose search method (linear/binary): ").lower()
try:
target = int(input("Enter the element to search: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
target = None
if target is not None:
if search_method == 'linear':
result = linear_search(arr, target)
elif search_method == 'binary':
arr.sort() # Binary search requires a sorted array
result = binary_search(arr, target)
else:
print("Invalid search method. Please choose 'linear' or 'binary'.")
result = -1
if result != -1:
print(f"Element {target} found at index {result}.")
else:
print(f"Element {target} not found in the list.")
OUTPUT:
Enter the elements of the array separated by space: 5 2 45 12 31 22
Entered Array: [5, 2, 45, 12, 31, 22]
Choose search method (linear/binary): linear
Enter the element to search: 12
Element 12 found at index 3.
Enter the elements of the array separated by space: 5 2 45 12 31 22
Entered Array: [5, 2, 45, 12, 31, 22]
Choose search method (linear/binary): binary
Enter the element to search: 31
Element 31 found at index 4.
No comments:
Post a Comment