Table of contents
1.
Introduction
2.
Key Features of Linear Search
3.
How Does Linear Search Algorithm Work?
4.
Implementation of Linear Search in C++
4.1.
C++
5.
Examples of Linear Search in C++
5.1.
Example 1: Searching for a Character in a String
5.2.
C++
5.3.
Example 2: Finding All Occurrences of an Element
5.4.
C++
6.
Time and Space Complexity of Linear Search
6.1.
Time Complexity
6.2.
Space Complexity
7.
Applications of Linear Search in C++
8.
Practical Implications
9.
Advantages of Linear Search in C++
10.
Disadvantages of Linear Search in C++
11.
Improving Linear Search Worst-Case Complexity
12.
When to Use Linear Search in C++?
13.
Frequently Asked Questions
13.1.
Is linear search faster than binary search?
13.2.
Can linear search be used on linked lists?
13.3.
When should I use linear search in C++?
13.4.
Why use linear search if it’s slow for large arrays?
14.
Conclusion
Last Updated: Oct 7, 2024
Easy

Linear Search in C++

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Linear search in C++ is one of the simplest and most intuitive search algorithms. It involves checking each element in a list or array sequentially until the desired element is found or the end of the structure is reached. It is not the most efficient for large datasets. Linear search is easy to implement and works well for small to medium-sized collections.

Linear Search in C++

In this article, we will learn how linear search works, its implementation in C++, examples, time & space complexity, advantages, disadvantages, & when to use linear search.

Key Features of Linear Search

The key features of linear search are:

  1. Simplicity: Linear search is straightforward to understand, making it a great starting point for beginners learning search algorithms.
  2. Sequential Access: The algorithm checks each element in the array or list one by one, starting from the first element and moving sequentially to the last.
  3. No Sorting Required: Linear search does not require the array or list to be sorted beforehand, making it versatile for any dataset.
  4. Works with Any Data Structure: It can be applied to arrays, linked lists, or any data structure that allows sequential access to its elements.
  5. Best Case Scenario: The best-case time complexity is O(1), which occurs when the element is found at the first position in the array or list.
  6. Worst Case Scenario: The worst-case time complexity is O(n), which occurs when the element is either not present or is located at the last position in the array or list.

How Does Linear Search Algorithm Work?

The linear search algorithm works by starting at the beginning of the list or array & comparing each element with the target element until a match is found or the end of the list is reached. Here's how it works step by step:

  1. Start at the first element of the list.
     
  2. Compare the current element with the target element.
     
  3. If the current element matches the target element, return its index.
     
  4. If the current element doesn't match, move to the next element in the list.
     
  5. Repeat steps 2-4 until the target element is found or the end of the list is reached.
     
  6. If the target element is not found, return -1 or a suitable indicator.

Implementation of Linear Search in C++

Implementation of the linear search algorithm in C++.

  • C++

C++

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
// Return the index of the found element
return i;
}
}
// Return -1 if the element is not found
return -1;
}

int main() {
int arr[] = {10, 25, 45, 30, 75, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;

int result = linearSearch(arr, n, key);

if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Element found at index: 3

Explanation: In this implementation, we declare an array arr[] with six integers and aim to find the index of a specific element, called the key, which is 30 in this case. The array's size is calculated using sizeof(arr) / sizeof(arr[0]). The linearSearch() function takes the array, its size, and the key as inputs. It iterates through the array using a for loop, returning the index if it finds the key. If the key isn't found, it returns -1. In the main() function, we call linearSearch() and store the result in result. If result isn't -1, the index of the key is printed; otherwise, the program indicates that the element isn't in the array. For this example, the output is "Element found at index: 3", as 30 is located at index 3. This simple implementation is effective for small datasets and demonstrates the basic concept of linear search.

Examples of Linear Search in C++

These examples will show how the same basic principle of linear search can be applied to various types of data and requirements.

Example 1: Searching for a Character in a String

Suppose you have a string and you want to check if a specific character is present in it. Here's how you can apply linear search to find a character in a string:

  • C++

C++

#include <iostream>
using namespace std;

int searchCharacter(string str, char target) {
for (int i = 0; i < str.length(); i++) {
if (str[i] == target) {
return i; // Return the index where the character is found
}
}
return -1; // Return -1 if the character is not found
}

int main() {
string myString = "Hello, world!";
char targetChar = 'w';

int result = searchCharacter(myString, targetChar);
if (result != -1) {
cout << "Character '" << targetChar << "' found at index: " << result << endl;
} else {
cout << "Character not found in the string." << endl;
}

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Character 'w' found at index: 7


In this example, if the target character 'w' is in the string "Hello, world!", the function returns its index, which would be 7.

Example 2: Finding All Occurrences of an Element

Sometimes, you might want to find all places where a specific element appears in an array, not just the first one. Here’s how you can modify the linear search to return all indices of the target value:

  • C++

C++

#include <iostream>
#include <vector>
using namespace std;

vector<int> findAllOccurrences(int arr[], int size, int target) {
vector<int> indices;
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
indices.push_back(i); // Add the index to the vector if the target is found
}
}
return indices; // Return all indices where the target is found
}

int main() {
int array[] = {1, 2, 3, 2, 4, 2, 5};
int target = 2;
int size = sizeof(array) / sizeof(array[0]);

vector<int> result = findAllOccurrences(array, size, target);
if (!result.empty()) {
cout << "Element found at indices: ";
for (int index : result) {
cout << index << " ";
}
cout << endl;
} else {
cout << "Element not found in the array." << endl;
}

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Element found at indices: 1 3 5 


This code will find all occurrences of the number 2 in the array and output "Element found at indices: 1 3 5".

Time and Space Complexity of Linear Search

Time and space complexity of an algorithm helps us evaluate its efficiency. For linear search, these complexities are straightforward but critical for understanding when and how to use the algorithm effectively.

Time Complexity

The time complexity of linear search is O(n), where 'n' is the number of elements in the array. This means that in the worst case, the algorithm might need to check every element once. This occurs when the target element is either at the end of the array or not present at all. In the best case, where the target is at the very beginning of the array, the time complexity is O(1), indicating an immediate find. However, the average case for finding an element is also O(n) because on average, half of the elements might need to be checked before finding the target.

Space Complexity

Linear search operates directly on the input data and does not require additional storage space that grows with the size of the input array. Therefore, its space complexity is O(1), which is considered excellent as it means the algorithm is very space-efficient. It simply requires space for one element comparison at a time, and does not need more than that, regardless of the array size.

Applications of Linear Search in C++

There are several applications of linear search in C++:

  • Unsorted Data Searching: Linear search is ideal for finding an element in unsorted arrays or lists where sorting is not possible or practical.
  • Small Datasets: For small collections of data, linear search is efficient and easy to implement without the need for complex algorithms.
  • Checking for Duplicates: It can be used to identify duplicate elements within a dataset by comparing each element with the others.
  • Finding the First Occurrence: Linear search can be used to find the first occurrence of a particular value in an array or list.
  • Real-Time Systems: In real-time systems where data is dynamically added, linear search is useful as it doesn't require preprocessing like sorting.
  • Sparse Data Structures: For sparse data structures, where most elements are empty or null, linear search efficiently locates non-null entries.
  • Searching Linked Lists: Since linked lists do not allow random access, linear search is often used to find elements in a linked list.
  • Multi-Dimensional Arrays: Linear search can be adapted to search through multi-dimensional arrays by treating them as one-dimensional arrays.
  • Iterative Solutions: In scenarios where recursive solutions are less desirable, linear search offers an iterative approach to finding elements.
  • Basic Search Algorithms: It's a fundamental search technique used as a building block or comparison baseline when developing or studying more complex search algorithms.

Practical Implications

Due to its O(n) time complexity, linear search is generally not suitable for large datasets where operations need to be highly efficient. It's most effective in scenarios where the datasets are small, not sorted, and there's no frequent need to search through them. The advantage of O(1) space complexity also makes linear search particularly appealing when working with memory constraints or in environments like embedded systems where memory is limited.

Advantages of Linear Search in C++

  • Simplicity: Linear search is straightforward to understand and implement. There are no complicated prerequisites or setup processes required before it can be used. This makes it an ideal teaching tool for introductory programming courses where basic concepts of searching need to be explained clearly and concisely.
  • No Need for Sorted Data: Unlike other searching algorithms like binary search, linear search does not require the data to be sorted before searching. This flexibility allows it to be used in applications where data is randomly ordered or where maintaining sorted data is impractical.
  • Efficiency on Small Data Sets: For small arrays or lists, linear search is very efficient, as the overhead of more complex algorithms might not justify their use. In cases where the list size is small, the simplicity and direct approach of linear search can often outperform more sophisticated methods.
  • Constant Space Requirement: Linear search operates with a constant space complexity of O(1). It requires no additional storage beyond the space needed for the input data. This minimal space requirement makes it suitable for systems with stringent memory constraints.
  • Detects All Occurrences: Linear search can easily be adapted to find all occurrences of a specific value within the array, not just the first one. This is particularly useful in applications where knowing the frequency and positions of all matches is necessary.
  • Useful for Unstructured Data: In scenarios where data cannot be easily structured or indexed, such as unlinked lists or streams of data, linear search remains one of the few viable options. It can be used effectively where other algorithms might fail or be too complex to implement.

Disadvantages of Linear Search in C++

  • Inefficient for Large Datasets: The biggest drawback of linear search is its inefficiency when dealing with large datasets. As the dataset grows, the time it takes to search through all the elements increases linearly, making it impractical for large-scale applications where performance is a critical factor.
  • Slower Compared to Other Algorithms: For sorted data, algorithms like binary search offer significantly faster performance by reducing the search space exponentially. Linear search, which scans each item sequentially, cannot compete with such efficiencies, particularly as the data size increases.
  • Performance Depends on Data Arrangement: The performance of linear search can vary greatly depending on the position of the target element. If the target is near the beginning of the dataset, the search is quick. However, if the target is at the end or absent, every element must be checked, resulting in maximum time consumption.
  • Not Scalable: Linear search does not scale well with dataset size. As applications grow and data accumulates, the time taken for linear searches increases, often making the system slower and less responsive.
  • No Index Utilization: Unlike indexed search methods, linear search does not take advantage of any pre-existing data structures that might organize or index the elements for quicker access. This lack of utilization leads to repeated and unnecessary comparisons.
  • Multiple Searches Are Cumbersome: If multiple searches are needed, linear search can be particularly inefficient. Each search operation starts from the beginning of the data structure, repeating the entire process even if the data has been searched before.

Improving Linear Search Worst-Case Complexity

Here’s how you can attempt to improve the worst-case performance of a linear search algorithm:

  • Sentinel Search: One modification to linear search is the introduction of a sentinel. This involves adding the target element to the end of the array. By doing this, you ensure that the search always succeeds by finding the target, thereby eliminating the condition check in the loop for reaching the end of the array. This can slightly improve performance by reducing the number of comparisons in each iteration.
  • Parallel Search: For systems with multiple processors or cores, implementing a parallel version of linear search can significantly speed up the process. By dividing the array into segments and searching through each segment simultaneously, the time required can be reduced proportionally to the number of processors used. This approach is particularly effective for very large datasets.
  • Improved Loop Efficiency: Minimizing the operations inside the search loop can also help. This includes reducing function calls or complex conditions inside the loop, and ensuring that only the most necessary operations are performed during each iteration.
  • Early Stopping: When possible, modifying the algorithm to stop as soon as a certain condition is met (other than finding the target) can save time. For example, if additional information about the likelihood of finding the target is known, the search can be halted early under certain circumstances.
  • Using More Efficient Data Structures: While this strays a bit from pure linear search, using more efficient data structures that suit the type of data and search operations can help. For example, if data is frequently searched, maintaining a sorted list or a hash table might be more efficient, even though the initial setup takes more time.
  • Algorithmic Refinement: Combining linear search with other algorithms based on the data characteristics can also optimize performance. For instance, switching to binary search if the dataset is sorted, or using hash maps for direct access if elements are non-sequential and unique.

When to Use Linear Search in C++?

Choosing the right time to use linear search is crucial for efficient programming. Despite its simplicity, there are specific scenarios where linear search is particularly advantageous. Here’s when you might choose to use linear search:

  • Small Data Sets: Linear search is ideal for small arrays or lists where the overhead of more complex algorithms does not provide significant benefits. In such cases, the simplicity and directness of linear search make it a quick and effective solution.
  • Unsorted Data: When data is not sorted and cannot be easily sorted due to constraints or the nature of the data, linear search remains a viable option. Since it does not require the data to be in any particular order, it can be used flexibly across various applications.
  • Single Search Operations: If you only need to perform a search operation once, or searches are infrequent, the setup time for more complex search algorithms might not justify their use. Linear search can be implemented quickly and without needing any additional data structures.
  • Real-Time Processing: In scenarios where data is being streamed in real-time, and immediate action is required based on incoming data, linear search allows for immediate processing without waiting for a complete dataset. This is useful in applications like live event monitoring or processing streaming data feeds.
  • Learning and Teaching: For educational purposes, linear search is an excellent algorithm because it introduces beginners to the concept of searching. It’s easy to understand and implement, making it an essential tool in teaching basic algorithmic concepts.
  • Applications with Low Resource Availability: In environments with limited computational resources, such as embedded systems or low-power devices, the low overhead and minimal space requirements of linear search can make it more suitable than more resource-intensive algorithms.

Frequently Asked Questions

Is linear search faster than binary search?

No, linear search is generally slower than binary search when dealing with sorted data. Binary search divides the search space in half with each step, significantly reducing the number of comparisons needed. Linear search, however, checks each element sequentially, which is less efficient on large datasets.

Can linear search be used on linked lists?

Yes, linear search is particularly useful for searching elements in linked lists, where accessing elements randomly is not possible. It works by traversing each node from the start to the desired element, making it a practical choice for this data structure.

When should I use linear search in C++?

Use linear search in C++ when dealing with small or unsorted datasets, where simplicity and ease of implementation are priorities. It's also ideal when you need to find the first occurrence of an element or when working with linked lists.

Why use linear search if it’s slow for large arrays?

Linear search can still be the right choice when dealing with small arrays, or when the data is unsorted and infrequent searches are required. Its simplicity and minimal resource requirements also make it suitable for systems with strict memory limitations.

Conclusion

In this article, we learned linear search in detail,like -:  how it works and where it can be effectively utilized. We learned how it cn be implemented in C++ with different examples, and analyzed its time and space complexity. Moreover, we looked at both the advantages and disadvantages of using linear search, providing insights into when and how to apply this algorithm optimally. Despite its simplicity, linear search offers significant benefits in the right contexts, particularly for small or unsorted data sets and in systems where complexity and resource use must be minimized. Understanding these fundamentals enables you to choose the best searching technique based on your specific requirements and constraints.

You can refer to our guided paths on Code360. Also, check out Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass