Searching Algorithms
Searching Algorithms
BFS= ABCDEFGHIJKLLMN
OUT PUT:
Depth First Search
DFS (Depth-first search) is a technique used for traversing
trees or graphs. Here backtracking is used for traversal. In this
traversal first, the deepest node is visited and then backtracks
to its parent node if no sibling of that node exists
Linear Search
Linear search is a search algorithm where a sequential search is made
over all items one by one. Every item is checked and if a match is found
then that particular item is returned, otherwise the search continues until
the end of the data collection.
How Does Linear Search Algorithm Work?
• In this algorithm,
• Divide the search space into two halves by finding the middle index
“mid”
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be
used as the next search space.
• If the key is smaller than the middle element, then the left side is used for next
search.
• If the key is larger than the middle element, then the right side is used for next
search.
• This process is continued until the key is found or the total search
space is exhausted.
Example
• Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target =
23.
• First Step: Calculate the mid and compare the mid element with the key. If the
key is less than mid element, move to left and if it is greater than the mid then
move search space to the right.
• Key (i.e., 23) is greater than current mid element (i.e., 16). The search space
moves to the right.
Key 23 is less than the current mid 56. The search space moves to the
left.
Second Step: If the key matches the value of the mid element, the
element is found and stop search.
Complexity Analysis of Binary Search:
• Time Complexity:
• Best Case: O(1)
• Average Case: O(log N)
• Worst Case: O(log N)
Class Activity
21 34 43 57 66 78 search 78
Search 9