3 Searching Algorithms
3 Searching Algorithms
and x = 5. {
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=0 {
arr[i] = 12
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=0 {
arr[i] = 12
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=1 {
arr[i] = 13
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=1 {
arr[i] = 13
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=2 {
arr[i] = 43
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=2 {
arr[i] = 43
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=3 {
arr[i] = 5
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
Linear Search Cont’d
int LS (int arr[], int N, int x)
x=5
i=3 {
arr[i] = 5
for (int i = 0; i < N; i++)
if (arr[i] == x)
return i;
12 3 43 5 67 34 23 45 21 4 return -1;
}
So, Location = 3
Linear Search Cont’d
Time Complexity:
Best Case: In the best case, the key might be present at the first index. So the best case
complexity is O(1)
Worst Case: In the worst case, the key might be present at the last index i.e., opposite to the end
from which the search has started in the list. So the worst-case complexity is O(N) where N is the
size of the list.
Average Case: O(N)
Binary Search
Binary search is a search algorithm used to find the position of a target value within a sorted array.
Algorithm:
Initialize two pointers: low (start of the list) and high (end of the list).
While low is less than or equal to high:
Calculate the middle index:
Home Task
1. Differentiate between Linear search and Binary search algorithm.
2. Advantages and Disadvantages of Linear search and Binary search algorithm.
Thank You