Understanding and Implementing Linear Search in C using Array. Linear search, also known as sequential search, is a straightforward method to find a specific element in a collection of data. In this article, we will explore the concept of linear search and guide you through the process of implementing a linear search program in the C programming language using arrays.
Table of Contents
Linear Search Overview
Linear search involves scanning a list or an array sequentially until the desired element is found. It is a simple and intuitive approach, but its time complexity is O(n), where n is the number of elements in the array. This means that the time taken to search for an element grows linearly with the size of the array
Linear Search Implementation in C using Array
Let’s walk through the step-by-step process of creating a C program that performs linear search on an array
#include <stdio.h>
// Function to perform linear search
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}
void main() {
int arr[] = {10, 5, 8, 3, 7, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int result = linearSearch(arr, n, key);
if (result != -1) {
printf("Element %d found at index %d\n", key, result);
} else {
printf("Element %d not found in the array\n", key);
}
}
Output
How the Above C Program Works
- The
linearSearch
the function takes an array, the number of elements n, and the key to be searched. It iterates through the array using a loop and returns the index if the key is found or -1 if it is not. - In the
main
function, we declare an arrayarr
and calculate its sizen
using thesizeof
operator. - In this case, we choose a key to search for
7
and call thelinearSearch
function. The result is stored in theresult
variable. - Finally, we check the result. If the index is not -1, we print the element’s index; otherwise, we indicate that the element was not found.