In this blog post, you will learn what is linear search and how to implement linear search in C with the help of programming examples.
So let’s first understand the linear search.
What is Linear Search?
Some people also call it sequential search. It is a method for finding an element within a list. It sequentially checks each element of the list until a match is found or the whole list has been searched.
Basic algorithm:
Suppose Arr
is a given integer array of n
elements. These elements are Arr0 , Arr1 , Arr2 , … Arrn-1 . And the target value T, the following steps are used to find the index of the target T in Arrn .
- Set i to 0.
- If Arri= T, the search terminates successfully; return “i”.
- Increase “i” by 1.
- If i < n, go to step 2. Otherwise, the search terminates unsuccessfully.
Now for a better understanding let’s see a problem statement. It also gives you the idea that how people ask questions in the interview related to linear search.
Problem Statement: Given an array of size n, and an element T, the task is to find T in the given array. If T is present print the index of the T or print -1.
Example 1: Input: arr[]= 11 22 13 14 15, num = 14 Output: 3 Explanation: 14 is present in the 3rd index Example 2: Input: arr[]= 1 14 31 12 10, num = 17 Output: -1 Explanation: 17 is not present in the given array
Now let’s see the solution but it is my recommendation that first try yourself before jumping directly on the solution.
Solution: Linear search in C:-
// Linear Search in C #include <stdio.h> int linearSearch(const int arr[], const int n, const int T) { int i =0; int elementIndex = -1; // Search sequencially in arr for (i = 0; i < n; i++) { if (arr[i] == T) { elementIndex = i; break; } } return elementIndex; } int main() { const int arr[] = {1, 23, 9, 31, 14}; const int T = 9; const int n = sizeof(arr) / sizeof(arr[0]); const int ret = linearSearch(arr, n, T); printf((ret != -1)? "Element Found":"Element not found"); return 0; }
Output:
Element Found
Recommended Post:
- C Programming Courses And Tutorials.
- CPP Programming Courses And Tutorials.
- Python Courses and Tutorials.
- Why is it faster to process a sorted array than an unsorted array?
- What is Binary Search?
- C program to find the most popular element in an array.
- C Program to find the largest and smallest element in an array.
- C program to move all zeroes to the end of array.
- Write a C program to find the sum of array elements.
- C program to find a duplicate element in an array.