Unit - II: Searching and
Sorting
MASTER SIMMI
[Lecturer]
Lecture 1: Introduction to
Searching
Objectives:
Understand the concept of searching in data
sets.
Learn about Linear Search and its
implementation.
Learn about Binary Search and its
implementation.
Topics Covered:
Introduction to Searching
Linear Search:
Definition
Algorithm
Time Complexity
Code Implementation (in Python and C)
Binary Search:
Definition
Algorithm
Time Complexity
Code Implementation (in Python and C)
Introduction to Searching
Concept:
Searching is the process of finding a specific item within a data
structure (e.g., an array or list).
It's important because it helps us quickly locate data, which is
fundamental in computing.
2. Linear Search
Definition:
Linear Search is a straightforward method of
searching where each element is checked
sequentially until the target is found or the list
ends.
Algorithm:
1. Start from the first element in the list.
2. Compare the current element with the target.
3. If they match, return the index of the current element.
4. If they don’t match, move to the next element and
repeat the process.
5. If the end of the list is reached without finding the
target, return -1 (indicating that the target is not
present).
Time Complexity:
•Best Case: O(1) (if the target is the first
element)
•Worst Case: O(n) (if the target is the last
element or not present)
•Average Case: O(n)
COD
E
int linear_search(int arr[], int size, int t) {
for (int i = 0; i < size; i++) {
if (arr[i] == t) {
return i;
}
}
return -1;
}
3. Binary Search
Definition:
Binary Search is an efficient algorithm for finding a
target value in a sorted array. It repeatedly divides the
search interval in half.
Algorithm:
1. Start with two pointers: low at the beginning and high at the end of
the array.
2. Calculate the middle index.
3. If the target equals the middle element, return the middle index.
4. If the target is less than the middle element, narrow the search to
the lower half.
5. If the target is greater, narrow the search to the upper half.
6. Repeat steps 2-5 until the target is found or the low pointer
exceeds the high pointer.
Time Complexity:
•Best Case: O(1) (if the target is the middle
element)
•Worst Case: O(log n) (since the search space is
halved each time)
•Average Case: O(log n)
int binary_search(int arr[], int size, int target) {
Code int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}