The Wayback Machine - https://web.archive.org/web/20240905210324/https://www.geeksforgeeks.org/c-c-program-for-linear-search/
Open In App

C Program for Linear Search

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
40.95%
3.7L

Linear Search is a sequential searching algorithm in C that is used to find an element in a list. Linear Search compares each element of the list with the key till the element is found or we reach the end of the list.

Example

Input: arr = {10, 50, 30, 70, 80, 60, 20, 90, 40}, key: 30
Output: Key Found at Index: 2
Explanation: Start from index 0, compare each element with the key (30). When index 2 is reached, the element (30) matches the target value.

Linear Search Algorithm

To search for the given element using linear search, follow the below approach:

  • Start traversing from the start of the dataset.
  • Compare the current element with the key (element to be searched).
  • If the element is equal to the key, return index.
  • Else, increment the index and repeat the step 2 and 3.
  • If we reach the end of the list without finding the element equal to the key, return some value to represent that the element is not found.

C Program to Implement Linear Search

C
// C program to implement linear search using loop
#include <stdio.h>

int linearSearch(int* arr, int n, int key) {
  
    // Starting the loop and looking for the key in arr
    for (int i = 0; i < n; i++) {

        // If key is found, return key
        if (arr[i] == key) {
            return i;
        }
    }

    // If key is not found, return some value to indicate
    // end
    return -1;
}

int main() {
    int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int key = 30;

    // Calling linearSearch() for arr with key = 43
    int i = linearSearch(arr, n, key);

    // printing result based on value returned by
    // linearSearch()
    if (i == -1)
        printf("Key Not Found");
    else
        printf("Key Found at Index: %d", i);

    return 0;
}

Output
Key Found at Index: 2

Complexity Analysis of Linear Search

  • Time Complexity: O(n), where n is the number of elements in the list.
  • Auxiliary Space: O(1)

How Linear Search Works?

The working of linear search is very simple. Let’s take an array arr = {10, 50, 30, 70, 80, 60, 20, 90, 40} and the key as 30.

Recursive Implementation of Linear Search

Just like most of the algorithms, linear search can also be implemented using recursion:

  • Define the recursive function that takes an array, its size, and the key as parameters.
  • Check if the current last element of the array is equal to the key.
    • If it is equal, return the index of it.
    • Otherwise, recursively call the linearSearch() with same array but with size decreased by one.
  • If the size reaches is 0, return -1 indicating the element is not found.

C Program to Implement Recursive Linear Search

C
// C Program to implement linear search using recursion
#include <stdio.h>

int linearSearch(int* arr, int n, int key) {
  
    // Base Case: if there are no elements, return -1
    if (n == 0)
        return -1;

    // If the element at (n - 1) index is equal to key,
    // return (n - 1)
    if (arr[n - 1] == key) {
        return n - 1;
    }

    // If element is not at n - 1, call linear search for
    // same array arr but reducing the size by a single
    // element
    return linearSearch(arr, n - 1, key);
}

int main() {
    int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
    int n = sizeof(arr) / sizeof(int);
    int key = 30;

    // Calling linearSearch function
    int i = linearSearch(arr, n, key);

    if (i == -1)
        printf("Key Not Found");
    else
        printf("Key Found at Index: %d", i);

    return 0;
}

Output
Key Found at Index: 2

Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(n)

Note: If the compiler performs tail call optimization, then Auxiliary Space for recursive approach can be reduced to O(1).

Linear Search in C – FAQs

When should I use a linear search?

Use linear search for small lists or when dealing with unsorted data. It is also useful when the simplicity of implementation is a priority.

What is the main drawback of linear search?

The main drawback is its inefficiency with large lists, as it requires checking each element individually, resulting in O(n) time complexity.

How can I improve the performance of linear search?

For sorted lists, consider using more efficient algorithms like binary search. For unsorted lists, if searches are frequent, consider using data structures that support faster search operations (e.g., hash tables).

Can linear search be used for linked lists?

Yes, linear search can be used for linked lists by traversing each node sequentially until the target value is found or the end of the list is reached.



Previous Article
Next Article

Similar Reads

Is Sentinel Linear Search better than normal Linear Search?
What is Sentinel Linear Search? Sentinel Linear search is a type of linear search where the element to be searched is placed in the last position and then all the indices are checked for the presence of the element without checking for the index out of bound case. The number of comparisons is reduced in this search as compared to a traditional line
9 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Difference Between Linear Search and Jump Search
Linear Search and Jump Search are two different techniques used to find an element in a list. Each algorithm has its own set of characteristics, advantages, and limitations, making them suitable for different scenarios. This article explores the key differences between Linear Search and Jump Search. What is Linear Search?Linear Search, also known a
3 min read
Difference between Linear and Non-linear Data Structures
Linear Data Structure: Data structure where data elements are arranged sequentially or linearly where each and every element is attached to its previous and next adjacent is called a linear data structure. In linear data structure, single level is involved. Therefore, we can traverse all the elements in single run only. Linear data structures are e
5 min read
C Program For Sentinel Linear Search
Sentinel Linear Search is basically a variation of the traditional linear search algorithm. It is designed to reduce the number of comparisons required to find a specific target value within an array or list. In this article, we will learn how to implement Sentinal Linear Search in C, see how it works, and compare its performance with traditional l
8 min read
Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading. Examples: Input : 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 20Key element foundInput :1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220Output :if key = 202Key not presentPrerequisite : Multi-threading Recommen
6 min read
Number of comparisons in each direction for m queries in linear search
Given an array containing N distinct elements. There are M queries, each containing an integer X and asking for the index of X in the array. For each query, the task is to perform linear search X from left to right and count the number of comparisons it took to find X and do the same thing right to left. In the end, print the total number of compar
7 min read
Sentinel Linear Search
Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-bounds comparisons, but there is no additional comp
12 min read
Linear Search Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Linear Search using JavaScript. We will see how the elements are being traversed in Linear Search until the given element is found. We will also visualize the time complexity of Linear Search. Reference: Linear SearchAsynchronous Functio
3 min read
What is Linear Search?
Linear search is defined as the searching algorithm where the list or data set is traversed from one end to find the desired value. Linear search works by sequentially checking each element in the list until the desired value is found or the end of the list is reached. Properties of Linear search :Time Complexity: The worst case time complexity of
3 min read
Improving Linear Search Technique
A linear search or sequential search 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. It is observed that when searching for a key element, then there is a possibility for searching the same key element again and again. The goal is that if t
15+ min read
What is linear search useful for?
Linear search is a fundamental search algorithm that iterates through a list of elements one by one, comparing each element to the target value. If the target value is found, the search stops and returns the index of the element. Otherwise, the search continues until the end of the list is reached, at which point it returns -1 to indicate that the
3 min read
Where is linear search used in real life?
Linear search is a fundamental searching algorithm that iterates through a list of elements one by one until the desired element is found. While it is not the most efficient searching algorithm for large datasets, linear search has several practical applications in real-life scenarios. 1. Finding Contact InformationLinear search can be found in app
2 min read
Does Linear Search require the list to be sorted?
Linear search is a simple search algorithm that iterates through a list of elements one by one until it finds the target element. It is often used when the list is small or unsorted. No, linear search does not require the list to be sorted. This is because linear search simply compares the target element to each element in the list, regardless of t
2 min read
Time and Space Complexity of Linear Search Algorithm
The time complexity of the Linear Search algorithm is O(n), where n is the number of elements in the array. The space complexity is O(1) as it requires a constant amount of extra space regardless of the input size. AspectComplexityTime ComplexityO(n)Space ComplexityO(1)Let's explore the detailed time and space complexity of the Linear Search Algori
2 min read
Two Way Linear Search Algorithm
Two-Way Linear Search Algorithm is based on the principle of Linear Search, but the search is conducted from both ends towards the center of the array. In this article, we will learn about the basics of Two Way Linear Search Algorithm, its advantages, implementation etc. What is Two-Way Linear Search?Two Way Linear Search is a searching technique w
6 min read
Introduction to Linear Search Algorithm
Linear Search Algorithm The linear search algorithm is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found; otherwise, the search continues till the end of the dataset. In this article, we will learn about the basics of the linear search algorithm, its applicatio
10 min read
Recursive Linear Search Algorithm
Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. How Linear Search Works?Linear search works by comparing each element of the data structure with the key to be found. To learn the w
6 min read
C Program for Anagram Substring Search (Or Search for all permutations)
Write a C program for a given text txt[0..n-1] and a pattern pat[0..m-1], the task is to prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Note: Expected time complexity is O(n) Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Inpu
6 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Anagram Substring Search (Or Search for all permutations) | Set 2
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Examples: Input: txt[] = "BACDGABCDA" pat[] = "ABCD"Output: Found at Index 0 Found at Index 5 Found at Index 6 Input: txt[] = "AAABABAA" p
10 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Anagram Substring Search (Or Search for all permutations)
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n &gt; m. Expected time complexity is O(n) Examples: 1) Input: txt[] = "BACDGABCDA" pat[] = "ABCD" Output: Found at Index 0 Found at Index 5 Found a
15 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
Sublist Search (Search a linked list in another list)
Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input: list1 = 10-&gt;20 list2 = 5-&gt;10-&gt;20 Output : LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;1-&gt;2-&gt;3-&gt;4 Output: LIST FOUNDInput: list1 = 1-&gt;2-&gt;3-&gt;4 list2 = 1-&gt;2-&gt;2-&gt;1-&gt;2-&gt;3 Outpu
15+ min read
Practice Tags :