KEMBAR78
Exp2 Linear Binary Search | PDF
0% found this document useful (0 votes)
25 views2 pages

Exp2 Linear Binary Search

The document presents a Python program that implements linear and binary search algorithms. Users can choose a search method, input an array, and specify a target number to search for. The program sorts the array for binary search and outputs the index of the found element or indicates if the element is not found.

Uploaded by

rj91721
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views2 pages

Exp2 Linear Binary Search

The document presents a Python program that implements linear and binary search algorithms. Users can choose a search method, input an array, and specify a target number to search for. The program sorts the array for binary search and outputs the index of the found element or indicates if the element is not found.

Uploaded by

rj91721
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Exp.

2: Linear Search & Binary Search


#Rahul_Rajkumar_Jadhav_COSC41

#linear search and binary search


def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1

def binary_search(arr, target):


left = 0
right = len(arr) - 1

while left <= right:


mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

# --- Main program ---


print("Choose search method:")
print("1. Linear Search")
print("2. Binary Search")

choice = input("Enter your choice (1 or 2): ")

# Get array input from user


user_input = input("Enter the array elements (separated by spaces): ")
arr = list(map(int, user_input.split()))
target = int(input("Enter the number to search (from array list): "))

if choice == '1':
result = linear_search(arr, target)
elif choice == '2':
arr.sort()
print("Sorted array:", arr)
result = binary_search(arr, target)
else:
print("Invalid choice.")
result = -1

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

Output:
Choose search method:
1. Linear Search
2. Binary Search
Enter your choice (1 or 2): 2
Enter the array elements (separated by spaces): 5 1 8 3 9
Enter the number to search (from array list): 3
Sorted array: [1, 3, 5, 8, 9]
Element found at index 1

=== Code Execution Successful ===

You might also like