Search Algorithm - 1
Linear Search and Binary Search
Index
• 1. Searching Algorithm Introduction, Why Need to
Search
• 2. Linear Search Theory and Code
• 3. Problem with Linear Search
• 4. Why Binary Search
• 5. Binary Search Theory and Code
• 6. Some Problems on Binary Search
• 7. Conclusion
Searching Algorithm Introduction
Searching is a fundamental operation in
computer science.
Purpose: To find the position of a target
element in a dataset.
• - Applications: Databases, file systems, and
real-time systems.
Why Need to Search
• - Access data quickly and efficiently.
• - Reduce time complexity in large datasets.
• - Improve performance in real-world
applications.
Linear Search Theory and Code
• - Linear search scans each element
sequentially.
• - Simple but inefficient for large datasets.
• - Time Complexity: O(n).
Linear Search Code
• def linear_search(arr, target):
• for i in range(len(arr)):
• if arr[i] == target:
• return i
• return -1
Problem with Linear Search
• - Inefficient for large datasets.
• - Requires O(n) comparisons in the worst case.
• - Not suitable for sorted datasets.
Why Binary Search
• - Optimized for sorted datasets.
• - Reduces search space by half in each step.
• - Time Complexity: O(log n).
Binary Search Theory and Code
• - Binary search works on sorted arrays.
• - Divide and conquer approach.
• - Efficient and widely used.
Binary Search Code
• def binary_search(arr, target):
• low, high = 0, len(arr) - 1
• while low <= high:
• mid = (low + high) // 2
• if arr[mid] == target:
• return mid
• elif arr[mid] < target:
• low = mid + 1
• else:
• high = mid - 1
• return -1
Some Problems on Binary Search
• 1. Finding the first and last occurrence of a
number.
• 2. Searching in a rotated sorted array.
• 3. Finding the square root of a number.
• 4. Median of two sorted arrays.
Conclusion
• - Searching algorithms are vital for data
retrieval.
• - Linear search is simple but inefficient for large
data.
• - Binary search is efficient and widely
applicable.
• - Mastering these algorithms is crucial for
problem-solving.