Linear search, also known as sequential search, is a fundamental search algorithm used to find the presence of a specific element within a collection of data. It works by iterating through each element of the data sequentially until the desired element is found or until all elements have been examined.
Advertise on this site. I promise you will like the rates :)
Linear search is a straightforward and intuitive algorithm that involves a simple step-by-step process:
Linear search is easy to understand and implement, making it a suitable choice for small datasets or cases where the data is not sorted. It is particularly useful when:
The time complexity of linear search is O(n), where "n" is the number of elements in the collection. In the worst case, the algorithm may need to examine every element in the collection before finding the target or determining its absence. This makes linear search less efficient for large datasets compared to algorithms with better time complexities, such as binary search (O(log n)).
Let's consider an example of searching for a specific number, say 7, in an array of integers: [3, 5, 2, 9, 7, 1, 8]. Starting from the first element, linear search would compare each element with the target, progressing through the array:
In this case, linear search found the target element (7) in the fifth iteration.
Here's an example of an C function that implements the linear search algorithm to find a target element within an array:
This code defines a linearSearch function that takes an array arr, its size size, and the target element target to search for. It iterates through the array, comparing each element with the target. If the target is found, it returns the index of the target element; otherwise, it returns -1 to indicate that the target is not present in the array.
In the main function, an example array is created, and the linearSearch function is called to search for the target element. The result is then printed to the console.
You can replace the arr, size, and target values in the main function with your own data to perform a linear search on a different array and target element.
Linear search is a basic search algorithm suitable for small datasets and unsorted collections. While it is straightforward to implement and easy to understand, its efficiency decreases for larger datasets due to its linear time complexity. For larger datasets or situations where performance is crucial, more advanced search algorithms, like binary search, offer better efficiency.