Searching Algorithm
Searching Algorithm
Searching algorithms are designed to retrieve specific elements or data from a collection. These
algorithms are fundamental in computer science, enabling tasks such as database queries, file
retrieval, and efficient data processing.
1. Introduction to Searching
Searching involves looking for an element within a dataset. The dataset can be unsorted, sorted, or
structured differently, such as in trees, graphs, or hash tables.
• Key Applications:
• Database queries.
• Information retrieval systems.
• Artificial intelligence and game development.
3. Linear Search
Description
Linear Search scans each element in a dataset until the desired value is found or the end is reached.
It is simple but inefficient for large datasets.
• Time Complexity:
• Best Case: O(1) (Element found at the beginning).
• Worst Case: O(n) (Element not found or at the end).
Algorithm (Pseudocode):
text
Copy code
function linearSearch(array, target):
for i = 0 to length(array) - 1:
if array[i] == target:
return i
return -1
Python Implementation:
python
Copy code
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
4. Binary Search
Description
Binary Search operates on sorted data by repeatedly dividing the search interval in half. It compares
the middle element with the target to decide the next search interval.
• Time Complexity:
• Best Case: O(1) (Middle element is the target).
• Average/Worst Case: O(logn).
Algorithm (Pseudocode):
text
Copy code
function binarySearch(array, target):
low = 0, high = length(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Python Implementation:
python
Copy 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
Advantages:
• Extremely efficient for large sorted datasets.
5. Hash-Based Searching
Description
Hashing uses a hash function to map data into a hash table, allowing constant-time search
operations in the average case.
• Time Complexity:
• Average Case: O(1).
• Worst Case: O(n) (Hash collisions).
Applications:
• Dictionary lookups.
• Cache mechanisms.
Python Example:
python
Copy code
hash_table = {1: "Alice", 2: "Bob", 3: "Charlie"}
target_key = 2
print(hash_table[target_key]) # Output: Bob
6. Tree-Based Searching
Binary Search Trees (BST)
BSTs are tree structures where the left child node is less than the parent, and the right child node is
greater.
• Search Complexity:
• Average Case: O(logn).
• Worst Case: O(n) (Degenerate tree).
Algorithm:
python
Copy code
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
Exponential Search
Efficient for searching in infinite or unbounded lists.