Lecture-4_Searching Algorithms
Lecture-4_Searching Algorithms
Searching Algorithms
1
Today’s Contents
• Different Types of Algorithms Algorithm?
• Searching Algorithms
• Complexity Analysis of Searching Algorithms
• Questions for You!
2
Algorithms we are going to study
1. Searching Algorithms
2. Sorting Algorithms
3. Greedy Approaches
4. Dynamic Programming
5. Graph Algorithms
3
Searching Algorithms
4
Searching Algorithms
5
Types of Searching Algorithms
▪ Based on the type of search operation, two popular
algorithms available:
6
1. Linear Search
7
Simulation of Linear Search
Check each and every data in the list till the desired element
or value is found.
8
Algorithm of Linear Search
Algorithm:
i = 1 flag = FALSE
while i <= n && Z != X[i] for i = 1 to n
do if A[i] == key
i = i+1
flag = TRUE;
if i < n then
FOUND if flag == TRUE
else FOUND
NOT FOUND else
NOT FOUND
9
Complexity Analysis of Linear Search
Algorithm:
flag = FALSE
for i = 1 to n
if A[i] == key
flag = TRUE;
• Best case: O(1)
if flag == TRUE
FOUND
• Worst Case: O(n)
else
NOT FOUND
10
Features of Linear Search Algorithm
11
2. Binary Search
▪ Binary Search is used with sorted array or list.
▪ In binary search, we follow the following steps:
– We start by comparing the element to be searched with the element in the
middle of the list/array.
13
14
15
16
Simulation of Binay Search
17
Algorithm of Binary Search
low = 1 //[Start position]
Algorithm:
high = n //[Last position]
flag = false
mid = (l+h) / 2
Xm = A[mid]
case:
Xm < Z : low = mid + 1
Xm > Z : high = mid - 1
Xm = = Z : flag = true
if flag = = true
FOUND
else
NOT FOUND
18
Search 55 mid
mid low mid low
low = 0
high = n-1
flag = false
if flag = = true
Step-3: mid = (low + high ) / 2 = (7 + 8) /2 = 7
FOUND
A[mid] = 55 == 55
else
NOT FOUND found
19
Complexity Analysis of Binary Search
• Best case:
• Worst Case:
20
Features of Binary Search
21
22
23
Complexity Analysis of Two Algorithms
24
Try to answer!
• If we have an array of length 70000000 but sorted, which
searching algorithm will work fast and why??
10 15 21 25 30 40 51 60
26
Thank you!
27