Introduction to Searching and Sorting Algorithms #
Welcome back to our programming tutorial series! Today, we’re exploring two fundamental concepts in computer science: searching and sorting algorithms. These algorithms are crucial for organizing and retrieving data efficiently, and you’ll encounter them in various real-world applications.
What Are Searching Algorithms? #
Searching algorithms are designed to retrieve specific elements from a collection of data. The most common searching algorithms include linear search and binary search.
Linear Search #
Linear search is the simplest searching algorithm. It works by checking each element in a list one by one until the desired value is found or the list ends.
Example: #
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Returns the index of the target
return -1 # If the target is not found
numbers = [10, 23, 45, 70, 11, 15]
print(linear_search(numbers, 70)) # Outputs: 3
print(linear_search(numbers, 100)) # Outputs: -1