Professional Documents
Culture Documents
Ex 11
Ex 11
Implement the Linear Search and Binary Search methods in two programmes to
discover any given element inside the provided range of numbers, and compare the
results to determine which algorithm is faster and/or uses less space.
ALGORITHM:
Algorithm – Linear Search
Input: List of numbers (arr), Target element to search (target)
Output: Index of the target element or -1 if not found
# Example usage:
if __name__ == "__main__":
array = list(range(1, 1000001))
target_element = 500000
start_time = time.time()
linear_search_result = linear_search(array, target_element)
end_time = time.time()
if linear_search_result != -1:
print(f"Linear Search: Element {target_element} found at index
{linear_search_result}.")
else:
print(f"Linear Search: Element {target_element} not found.")
OUTPUT:
Linear Search: Element 500000 found at index 499999.
Time taken for Linear Search: 0.021607398986816406 seconds.
PROGRAM: Binary
import time
if mid_element == target:
return mid
elif mid_element < target:
low = mid + 1
else:
high = mid - 1
return -1
# Example usage:
if __name__ == "__main__":
array = list(range(1, 1000001))
target_element = 500000
start_time = time.time()
binary_search_result = binary_search(array, target_element)
end_time = time.time()
if binary_search_result != -1:
print(f"Binary Search: Element {target_element} found at index
{binary_search_result}.")
else:
print(f"Binary Search: Element {target_element} not found.")
OUTPUT:
Binary Search: Element 500000 found at index 499999.
Time taken for Binary Search: 1.1444091796875e-05 seconds.
COMPARISON:
• Run both programs and observe the time taken for each search.
• Typically, Binary Search will be significantly faster than Linear Search for large
datasets.
• The space complexity for both algorithms is low, as they don't use additional space
proportional to the input size.
• Note: The efficiency of Binary Search becomes more apparent with larger datasets or
repeated searches, as it operates with a time complexity of O(log n), while Linear
Search has a time complexity of O(n).