Linear Search is one of the simplest searching algorithms in Data Structures and Algorithms (DSA). It works by traversing through each element in a list and comparing it with the target value. If the element is found, its index is returned; otherwise, the search continues until the end of the list.
function linearSearch(arr, target): for i = 0 to length of arr - 1: if arr[i] == target: return i // Element found return -1 // Element not found
#include <stdio.h> int linearSearch(int arr[], int n, int target) { for (int i = 0; i < n; i++) { if (arr[i] == target) { return i; // Element found, return index } } return -1; // Element not found } int main() { int arr[] = {2, 5, 7, 9, 11, 15}; int n = 6; int target = 9; int result = linearSearch(arr, n, target); if (result != -1) printf("Element found at index %d\n", result); else printf("Element not found\n"); return 0; }
The time complexity of Linear Search is O(n), where 'n' is the number of elements in the array. In the worst case, the algorithm may need to traverse all elements in the list to find the target element.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!