Searching Algorithm
Searching Algorithm
Linear Search is a simple and straightforward searching algorithm that scans each element of a list sequentially until
the target element is found or the end of the list is reached. It is also known as a sequential search.
Algorithm (Linear Search): The linear search algorithm follows these steps:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 30;
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}
Complexity Analysis of Linear Search : Let n be the number of elements in the array.
• On average, the search finds the target somewhere in the middle of the list.
• It performs approximately n/2n comparisons.
• In Big-O notation, it is still O(n).
Worst Case O(n) If the element is at the last position or not present.
Average Case O(n) On average, we search half the elements, leading to O(n)O(n)O(n).
if (arr[mid] == target)
return mid; // Element found
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 30;
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}
Complexity Analysis of Binary Search
Case Complexity Explanation
Worst Case O(logn) The search space is reduced by half at each step.
Average Case O(logn) The expected number of comparisons follows the logarithmic pattern.
Recursive Binary Search O(logn) Due to recursive function calls (stack memory).