Linear search is one of the simplest and most straightforward searching algorithms. It is used to find a specific element within a list or array. While linear search might not be the most efficient searching algorithm for large datasets, it serves as a fundamental concept in computer science and is often used as a building block for more advanced search algorithms.
In this article, we will explore how to implement linear search in the C programming language and discuss some of its characteristics, use cases, best practices, and linear search using functions in C programming. But before starting the preparation regarding swapping, consider learning these C Certification Courses.
Linear search operates by sequentially checking each element of an array or list until a match is found or the end of the list is reached. This search process can be likened to reading a book page by page to find a specific word, you start at the beginning and keep scanning until you either find the word or reach the end of the book.
Here are the key steps of a linear search algorithm:
Start at the beginning of the list or array.
Compare the target element with the current element.
If the target element is found, return its index or position.
If the target element is not found, move to the next element in the list.
Repeat steps 2-4 until the end of the list is reached.
Implementing Linear Search in C
Let us walk through the process of implementing a linear search in C with a simple example. We will create a function that searches for a target element in an array and returns its index or a value indicating that the element was either found or not found.
#include <stdio.h>
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, return -1
}
int main() {
int data[] = {10, 24, 6, 31, 42, 8, 50, 18};
int dataSize = sizeof(data) / sizeof(data[0]);
int target = 42;
int result = linearSearch(data, dataSize, target);
if (result != -1) {
printf("Element %d found at index %d\n", target, result);
} else {
printf("Element %d not found in the array\n", target);
}
return 0;
}
In this example, we have a simple linearSearch function that takes three parameters:
arr[]: The array in which we want to search.
size: The size of the array.
target: The element we are searching for.
The function iterates through the array and returns the index of the target element when it is found. If the element is not found after checking all elements, the function returns -1.
The main function demonstrates the usage of linearSearch by searching for the element 42 in the data array. It prints the result to the console.
Also read:
Characteristics and Complexity of Linear Search are fundamental aspects to consider when working with this straightforward yet essential searching algorithm in computer science. Linear search, also known as sequential search, operates by systematically comparing each element in an array or list until a matching element is found or the end of the list is reached. Linear search has several characteristics and complexities:
Time Complexity: Linear search has a time complexity of O(n), where 'n' is the number of elements in the array. This means that the time it takes to find an element increases linearly with the size of the array.
Space Complexity: Linear search has a space complexity of O(1), as it does not require any additional data structures or memory.
Unsorted Data: Linear search can be used on both sorted and unsorted data. However, it's most efficient when the data is unsorted because there's no way to take advantage of ordering.
Use Cases: Linear search is best suited for small datasets or when you only need to perform occasional searches within a dataset. For larger datasets, more efficient search algorithms such as binary search or hash tables are preferred.
Worst-Case Scenario: The worst-case scenario for a linear search is that the target element is the last element in the array or not present at all. In these cases, you would need to traverse the entire array.
Best-Case Scenario: The best-case scenario is that the target element is found at the beginning of the array. In this case, the search would be very efficient, but it's important to remember that the best-case scenario rarely occurs in practice.
Also Read:
When implementing the linear search algorithm, incorporating best practices and optimisation techniques is essential to ensure its efficiency and maintainability. While linear search is straightforward, there are some best practices and optimisations you can implement to make it more efficient and maintainable:
Early Exit: If you have control over the data, consider placing the elements you're likely to search for at the beginning of the array. This can optimise the best-case scenario.
Function Reusability: Wrap the linear search logic in a function, as shown in the example. This makes it easier to reuse the code and keeps your program organised.
Error Handling: Handle the case where the target element is not found. In the example, we return -1, which is a common practice.
Validation: Check the input parameters for validity, such as ensuring that the array is not empty and the size is non-negative.
Consider Alternative Data Structures: If you frequently need to search for elements, consider using data structures such as hash tables or binary search trees for improved efficiency.
Linear search is a straightforward and commonly used searching algorithm in the realm of computer programming. This algorithm is employed to search for a specific element within an array or list by sequentially examining each element until a match is found or the end of the list is reached. To make the implementation of a linear search program in C more modular and reusable, it is a common practice to encapsulate the search logic within a function. Let us explore this with a practical example about linear search using functions in C.
Also read: Free Programming Courses & Certifications
Consider an array of integers:
int numbers[] = {12, 34, 6, 45, 78, 54, 89, 23};
Now, you want to find whether a specific number, let us say 45, exists in this array using linear search. By creating a dedicated function for linear search, the code becomes more organised and easier to maintain:
#include <stdio.h>
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, return -1
}
int main() {
int numbers[] = {12, 34, 6, 45, 78, 54, 89, 23};
int size = sizeof(numbers) / sizeof(numbers[0]);
int target = 45;
int result = linearSearch(numbers, size, target);
if (result != -1) {
printf("Element %d found at index %d\n", target, result);
} else {
printf("Element %d not found in the array\n", target);
}
return 0;
}
In this example, we have defined a linear search using a function in C, which accepts three arguments: the array to search (arr[]), the size of the array (size), and the target element we want to find (target). Inside the function, we iterate through the array, comparing each element with the target value. If a match is found, the index of the element is returned (please note here that the index starts from 0) ; otherwise, -1 is returned to indicate that the element was not found.
By practicing the linear search using functions in C, you can reuse this functionality across your C programs. It promotes code reusability, readability, and modularity. This approach not only simplifies the main program logic but also makes it easier to update or optimise the search algorithm as needed. So, whether you are searching for a number in an array, a name in a list, or any other element in a collection, the linear search using function in C provides a valuable tool for the task.
Related: C Certification Courses By Top Providers
Linear search is a basic but fundamental searching algorithm in computer science. It is a valuable concept to understand, especially for those learning programming or algorithms. While it may not be the most efficient search algorithm for large datasets, it serves as a starting point for more advanced search techniques.
In this article, we have implemented a simple linear search in C, discussed its characteristics and complexities, and provided some best practices for optimising and using the algorithm effectively. Apart from that we also explore the linear search using function in C. As you become more familiar with programming and data structures, you will discover that there are more efficient search algorithms available, and will excel your journey as a proficient computer programmer, therefore we can say that linear search will always have its place as a straightforward and reliable way to find elements in an array or list.
Linear search, also known as sequential search, is a basic searching algorithm used to find a specific element within an array or list. It is often employed for small datasets or when you need to perform occasional searches within a collection.
Linear search has a time complexity of O(n), where 'n' is the number of elements in the array, and a space complexity of O(1), meaning it does not require additional data structures or memory.
Yes, linear search can be used for both sorted and unsorted data. However, it is most efficient when applied to unsorted data since sorting doesn't provide an advantage.
It works by sequentially comparing each element with the target element until a match is found or the end of the list is reached.
The primary components of a linear search algorithm in C include iterating through the array, comparing elements with the target, and returning the index of the target element if found, or -1 if not found.
Application Date:15 October,2024 - 15 January,2025
Application Date:11 November,2024 - 08 April,2025