Lecture_5
Lecture_5
for(int i=0;i<n;i++){
if(x[i]==item) return true;
else return false;
}
return false;
}
Linear Search - Time Complexity
left + right
mid =
2
Binary Search
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target)
return mid; // Element found
• Small datasets.
• When the data is unsorted.
• If simplicity is more important than
efficiency.
When to Use Binary Search?
• Large datasets.
• When the data is already sorted.
• If you need fast and efficient
searching performance.
Big-O Recap
• Linear Search:
– Best Case: O(1)
– Worst Case: O(n)
• Binary Search:
– Best Case: O(1)
– Worst Case: O(log n)
Summary of Key Concepts
• Linear Search is straightforward but
inefficient for large arrays.
• Binary Search is a faster algorithm but
works only on sorted arrays.
• Understanding the Big-O complexity
helps choose the right search method
for the task.