Searching in PPS
Searching in PPS
• 2. Binary Search:
• - Works on sorted data by dividing the
search space into halves.
• - Time Complexity: O(log n)
Linear vs Binary Search
• Linear Search:
• • Works on unsorted data
• • Time Complexity: O(n)
• • Easy to implement
• Binary Search:
• • Requires sorted data
• • Time Complexity: O(log n)
• • More efficient for large datasets
Applications of Searching
• • Database Management Systems
• • Search Engines
• • E-commerce platforms (finding products)
• • Navigation Systems
• • Cybersecurity (pattern matching)
Linear Search Algorithm
• Algorithm:
• 1. Start at the first element.
• 2. Compare the target with the current
element.
• 3. If a match is found, return the index.
• 4. If no match is found, move to the next
element.
• 5. Repeat until the end of the list.
Binary Search Algorithm
• Algorithm:
• 1. Start with the middle element of the sorted
list.
• 2. Compare the target with the middle
element.
• 3. If it matches, return the index.
• 4. If the target is smaller, search the left half.
• 5. If the target is larger, search the right half.
• 6. Repeat until the target is found or the
Linear Search Code (Python)
• def linear_search(arr, target):
• for i in range(len(arr)):
• if arr[i] == target:
• return i
• return -1
• # Example:
• arr = [10, 20, 30, 40]
• target = 30
Binary Search Code (Python)
• 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: