0% found this document useful (0 votes)
1K views2 pages

DSL PR2

The document describes two search algorithms for an e-commerce system: Linear Search and Binary Search. Linear Search checks each element in a list for a match, while Binary Search requires a sorted list and improves efficiency by dividing the search space. Code examples for both methods are provided, demonstrating their functionality with customer account IDs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views2 pages

DSL PR2

The document describes two search algorithms for an e-commerce system: Linear Search and Binary Search. Linear Search checks each element in a list for a match, while Binary Search requires a sorted list and improves efficiency by dividing the search space. Code examples for both methods are provided, demonstrating their functionality with customer account IDs.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

DSL

2. In an e-commerce system, customer account IDs are stored in


a list, and you are tasked with writing a program that
implements the following:
a) Linear Search: Check if a particular customer account ID
exists in the list.
b) Binary Search: Implement Binary search to find if a customer
account ID exists, improving the search efficiency over the basic
linear.

a) Linear Search

Linear search goes through each element one by one until it


finds a match or reaches the end of the list.

def linear_search(account_ids, target_id):


for account_id in account_ids:
if account_id == target_id:
return True
return False

Example:

accounts = [101, 202, 303, 404,505]


print(linear_search(accounts, 303)) # Output: True
print(linear_search(accounts, 999)) # Output: False
b) Binary Search

Binary search is much faster but requires the list to be sorted.

def binary_search(account_ids, target_id):


account_ids.sort() # Ensure the list is sorted
left, right = 0, len(account_ids) - 1

while left <= right:


mid = (left + right) // 2
if account_ids[mid] == target_id:
return True
elif account_ids[mid] < target_id:
left = mid + 1
else:
right = mid - 1
return False

Example:

accounts = [101, 202, 303, 404, 505]


print(binary_search(accounts, 303)) # Output: True
print(binary_search(accounts, 999)) # Output: False

You might also like