Day 3 of DSA Journey: Searching Like a Pro – Linear vs Binary Search
Today’s focus:
Linear Search vs Binary Search
📌 1. Linear Search (Brute Force Way)
Search every element one by one.
int linearSearch(int arr[], int n, int target) {
for(int i = 0; i < n; i ) {
if(arr[i] == target)
return i;
}
return -1;
}
✅ Works on unsorted arrays
⏱ Time Complexity: O(n)
🧠 Simple but not optimal for large data
⚡ 2. Binary Search (Divide & Conquer)
Only works on sorted arrays. It cuts the search space in half each time.
int binarySearch(int arr[], int n, int target) {
int low = 0, high = n - 1;
while(low <= high) {
int mid = low (high - low) / 2;
if(arr[mid] == target)
return mid;
else if(arr[mid] < target)
low = mid 1;
else
high = mid - 1;
}
return -1;
}
⚠️ Only works on sorted arrays
⏱ Time Complexity: O(log n)
🧠 Super efficient for big datasets
🧩 Challenge of the Day:
> ✍️ Given a sorted array of integers, write a function to check if a target element exists using Binary Search.
Bonus: Try writing it recursively as well!
That’s all for Day 3, friends!
Tomorrow, we’ll dive into Sorting Algorithms — starting with Bubble, Selection, and Insertion Sort.
If you like the post. Please like and follow me for the DSA Journey.