Searching a value in Array Data Structure

As a beginner in the world of programming, you’ll often find yourself dealing with arrays—a fundamental data structure that stores collections of elements. Understanding how to search for a specific element within an array is an essential skill. In this article, we’ll introduce you to one of the simplest yet effective searching algorithms: the Linear Search.

Linear Search, also known as Sequential Search, is a straightforward algorithm for finding a particular element in an array. It works by scanning each element in the array, one at a time, until the desired element is located or the entire array has been searched. This method is similar to flipping through the pages of a book to find a specific sentence — you start at the beginning and go through each page until you find the sentence you’re looking for.


#include <stdio.h>

// Function to perform a linear search
int linearSearch(int arr[], int size, int target) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            return i; // Element found, return its index
        }
    }
    return -1; // Element not found
}

int main() {
    int arr[] = {12, 34, 45, 9, 67, 23};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 67;
    
    int result = linearSearch(arr, size, target);
    
    if (result != -1) {
        printf("Element found at index %d\n", result);
    } else {
        printf("Element not found in the array\n");
    }
    
    return 0;
}

Here’s a breakdown of how the code works:

  • We declare a function linearSearch that takes three arguments:
    • the array to be searched
    • its size
    • and the target element we want to find
  • Inside this function, we use a for loop to iterate through the array elements.
  • During each iteration, we check if the current element (arr[i]) matches the target element (target).
  • If they match, we return the index at which the element was found.
  • If the loop completes without finding the element, we return -1 to indicate that the element is not in the array.
  • In the main function, we define an integer array and call linearSearch to search for a specific element (target).
  • Depending on whether the element is found or not, we print an appropriate message.

Conclusion

Linear search is a fundamental and intuitive algorithm for searching elements in an array. It is easy to implement and is suitable for small arrays or unsorted data. However, for larger datasets, there are other way to search for an element like binary search, sets, bloom filters etc. As you continue your programming journey, you’ll encounter various searching and sorting techniques that will help you tackle more complex problems. Linear search is just the beginning, and mastering it will set a solid foundation for your programming skills.