Javatpoint Logo
Javatpoint Logo

Linear Search Algorithm in C++

Introduction:

Algorithms play a fundamental role in computer science and programming, as they allow us to solve various problems efficiently and effectively. One such algorithm is the linear search, a straightforward but essential search algorithm that helps us find a specific element in a collection of data. In this article, we will delve into the linear search algorithm in C++, its principles, and how to implement it.

What is Linear Search?

Linear search, also known as sequential search, is a basic algorithm for finding a specific element within a list or array. It follows a simple and intuitive approach, where it examines each element in the data structure one by one, until the desired element is found or until the end of the data structure is reached.

Evolution:

  1. Early Computer Science: Linear search has its roots in the early days of computer programming. In the mid-20th century, when computers were in their infancy, programmers needed a simple way to locate specific data within datasets. Linear search was a natural and straightforward approach.
  2. Manual Card Sorting: Before electronic computers, linear search was used in manual data processing. For example, in libraries and administrative tasks, card catalogs were manually sorted, and individuals would sequentially search through these cards to find specific information.
  3. Early Programming Languages: As programming languages were developed, linear search became a fundamental part of computer programming. Early programming languages like Fortran and COBOL relied on linear search for data retrieval and processing.
  4. Textbook Algorithms: Linear search was often included in textbooks and educational materials to introduce programming concepts to students. It served as a simple yet practical example of an algorithm.
  5. Influence on Algorithm Design: The concept of linear search influenced the development of more advanced searching algorithms. Computer scientists and programmers built on the principles of linear search to create more efficient algorithms like binary search, which takes advantage of sorted data.
  6. Persistence in Software Development: While linear search is not always the most efficient choice for large datasets, it continues to have a place in software development. It is used in various applications where simplicity, ease of implementation, and data structure constraints make it a practical option.
  7. Education and Learning: Linear search remains a fundamental concept in computer science education. It is often one of the first searching algorithms students encounter, helping them build a foundation in algorithm design and problem-solving.
  8. Real-World Applications: Linear search is still used in real-world applications, especially when dealing with small datasets or in scenarios where other algorithms may not be necessary. It is employed in tasks such as searching for elements in lists, databases, and simple data structures.

Key Features of Linear Search:

  • Simplicity: Linear search is one of the simplest searching algorithms. It is easy to understand and implement, making it a suitable choice for small datasets.
  • Unordered Data: Linear search works well on both ordered and unordered data, as it checks each element individually.
  • Time Complexity: Linear search has a time complexity of O(n), where 'n' represents the number of elements in the dataset. This means that in the worst-case scenario, the algorithm might have to scan through all elements.
  • No Data Manipulation: Unlike some search algorithms, linear search doesn't require data to be sorted or manipulated in any way before performing the search.

Time and Space Complexity:

Time Complexity of Linear Search:

The time complexity of the linear search algorithm is O(n), where "n" represents the number of elements in the dataset being searched. In linear search, the algorithm scans through the data sequentially, comparing each element with the target value until it either finds a match or reaches the end of the dataset. In the worst-case scenario, the target element may be the last element in the dataset, which requires checking every element. Therefore, the time complexity is linear, and the running time increases linearly with the size of the input data.

Space Complexity of Linear Search:

The space complexity of the linear search algorithm is O(1), which means it uses a constant amount of memory. Linear search does not require additional data structures that scale with the input size. It only uses a few variables to keep track of the loop index, the target value, and the result (index of the found element or -1 if not found). Regardless of the size of the dataset, the space used remains constant.

Implementing Linear Search in C++:

Let's take a closer look at how to implement the linear search algorithm in C++. We'll provide a simple code example to help you understand the process.

Output:

Element found at index 6

Explanation:

1. Initialization:

  • First, you have an array (or list) of elements in memory.
  • You also have a target value that you want to find within this array.

2. Iteration:

  • Start at the first element in the array.
  • Compare the value of the current element with the target value.

3. Check for a Match:

  • If the current element is equal to the target value, you've found a match!
  • In this case, you return the index (position) of the current element in the array. This index is usually a non-negative integer that represents the element's position within the array.

4. No Match:

  • If the current element is not equal to the target value, move to the next element in the array.
  • Repeat this process (comparing the current element with the target value) for each element in the array one by one.

5. End of the Array:

Continue iterating through the array until you find a match, or you reach the end of the array without finding the target value.

6. Reporting the Result:

  • If you find the target value, you return the index of the element.
  • If you reach the end of the array without finding the target value, you return a special value (commonly -1) to indicate that the target value was not found in the array.

Key Points:

  • Linear search is a straightforward and intuitive algorithm.
  • It's not dependent on the order of elements in the array; it works for both ordered and unordered data.
  • Its time complexity is O(n), where 'n' is the number of elements in the array. In the worst case, you may have to check all elements.
  • It doesn't require any preprocessing of data, such as sorting, before searching.
  • It's suitable for small datasets but less efficient for very large datasets.

In summary, the linear search algorithm is a basic method for finding a specific element in an array or list by examining each element one by one until the desired element is found or the end of the data structure is reached. It serves as a fundamental building block for understanding more advanced searching algorithms and data structures.

Example 1: Searching for an Element in an Array

In this example, we have an array of integers, and we want to find a specific element in the array using linear search.

Output:

Element found at index 6

Explanation:

  1. define a function called linearSearch that takes three arguments:
    • arr[]: an array of integers where we want to search.
    • n: the size of the array.
    • target: the integer we want to find.
  2. Inside the linearSearch function:
    • We use a for loop to iterate through each element in the array, starting from the first element (index 0) and going up to the last element (index n - 1).
    • For each element in the array, we compare it with the target value.
    • If the element matches the target, we return the index of that element, indicating that we found the element.
  3. If the for loop completes without finding the target (i.e., none of the elements match the target), we return -1 to signify that the element was not found in the array.
  4. In the main function, we create an array called data and initialize it with a set of integer values.
  5. We determine the size of the data array using the sizeof operator to calculate n.
  6. We specify the target value that we want to find within the array (e.g., target = 67).
  7. We call the linearSearch function with the data array, its size n, and the target value as arguments.
  8. The result of the search is stored in the result variable.
  9. We then use conditional statements to check the value of result. If result is not equal to -1, we print a message indicating the index where the element was found. If result is -1, we print a message indicating that the element was not found in the array.

Example 2: Searching for a Name in a List

In this example, we have a list of names stored in a C++ vector, and we want to find a specific name in the list using linear search.

Output:

Name found at index 4

Explanation:

  1. We define a function called linearSearch that takes two arguments:
    • names: a vector of strings where we want to search.
    • target: the name we want to find.
  2. Inside the linearSearch function:
    • We use a for loop to iterate through each name in the vector.
    • For each name in the vector, we compare it with the target name.
    • If the name matches the target, we return the index of that name, indicating that we found the name.
  3. If the for loop completes without finding the target (i.e., none of the names match the target), we return -1 to signify that the name was not found in the vector.
  4. In the main function, we create a vector called nameList and initialize it with a set of names.
  5. We specify the targetName that we want to find within the vector (e.g., targetName = "Eve").
  6. We call the linearSearch function with the nameList vector and the targetName as arguments.
  7. The result of the search is stored in the result variable.
  8. We then use conditional statements to check the value of result. If result is not equal to -1, we print a message indicating the index where the name was found. If result is -1, we print a message indicating that the name was not found in the vector.

Example 3: Searching for a Student's Grade in an Array of Structures

In this example, we have an array of structures representing student records, and we want to find the grade of a specific student using linear search.

Output:

Grade for David is 88

Explanation:

  1. We start by defining a structure named Student. Each Student structure has two members: name (a string to store the student's name) and grade (an integer to store the student's grade).
  2. We create a function called linearSearch that takes three parameters:
    • students[]: an array of Student structures.
    • n: the number of elements in the array.
    • targetName: the name of the student whose grade we want to find.
  3. Inside the linearSearch function:
    • We use a for loop to iterate through each element of the students array.
    • For each student, we check if the name member of the Student structure matches the targetName we're searching for.
    • If a match is found, we return the grade of that student, indicating that we found the student's record.
  4. If the for loop completes without finding the student with the specified name, we return -1 to signify that the student was not found in the array.
  5. In the main function, we create an array of Student structures named studentData and initialize it with records of students, including their names and grades.
    • We determine the number of elements in the studentData array using the sizeof operator to calculate n.
    • We specify the targetName (e.g., "David") for which we want to find the grade.
    • We call the linearSearch function, passing the studentData array, its size n, and the targetName as arguments.
    • The result of the search is stored in the result variable.
  6. We use conditional statements to check the value of result. If result is not equal to -1, we print a message indicating the grade for the student with the name targetName. If result is -1, we print a message indicating that the student's record was not found in the array.

Example 4: Checking for the Presence of a Character in a String

In this example, we want to check if a specific character is present in a string using linear search.

Output:

Character 'W' is present in the string.

Explanation:

  • Function Declaration: We create a function named linearSearch that takes two parameters:

text: This is the string in which we want to search for the character.

targetChar: This is the character we want to check for within the string.

  • Searching Within the String:

Inside the linearSearch function, we use a for-each loop to iterate through the characters in the text string.

For each character, we compare it with the targetChar that we're searching for.

Character Found:

If a match is found, meaning the current character is the same as the targetChar, we return true. This indicates that the character is present in the string.

Character Not Found:

If the loop completes without finding the targetChar in the string, we return false. This indicates that the character is not present in the string.

  • Main Function:

In the main function, we define the input string text (e.g., "Hello, World!") and specify the targetChar (e.g., 'W') that we want to check for.

Calling the Linear Search Function:

We call the linearSearch function, passing the text string and the targetChar as arguments.

  • Result Handling:

The result of the search is stored in the result variable.

  • Displaying the Result:

We use conditional statements to check the value of result. If result is true, we print a message indicating that the character is present in the string. If result is true, we print a message indicating that the character is present in the string. If result is false, we print a message indicating that the character is not found in the string.

This code demonstrates how linear search can be used to check for the presence of a specific character within a given string. The algorithm scans through the characters in the string sequentially and returns true if the character is found or false if it is not found.

Applications:

  • Find Operations in Unsorted Lists: When you have an unsorted list of items, and you want to find a specific item, linear search is a straightforward choice. This can be useful in tasks like finding a name in a contact list or locating a specific record in an unsorted database.
  • Searching in Simple Databases: In small-scale databases where records are not indexed or organized in a particular way, linear search can be used to find specific records based on certain criteria.
  • Input Validation: Linear search can be employed to validate user input by checking if a given value exists in a predefined list of valid options or in a configuration file.
  • Checking for Duplicates: Linear search can identify duplicate entries within a dataset. It's useful in data cleaning and de-duplication processes.
  • Linear Search as a Building Block: Linear search is often used as a foundational concept for understanding more complex search algorithms. It provides a starting point for learning binary search, hash tables, and other advanced searching techniques.
  • Web Browsers and Text Editors: Linear search is used in web browsers and text editors to find specific words or phrases within a document.
  • Computer Games: Linear search can be used to find objects or enemies in 2D games or simple game grids. While it may not be the most efficient algorithm for complex game environments, it's suitable for basic scenarios.
  • Control Flow Logic: Linear search can be applied to control flow logic. For example, you might use it to determine which path a program should follow based on a specific condition.
  • Network Routing: In certain routing algorithms, linear search may be used to find a matching rule for routing packets based on criteria like IP addresses or port numbers.
  • Resource Management: In scenarios where resources (such as memory blocks) are allocated or released, linear search can help identify available resources.

It's important to note that while linear search is a versatile algorithm, it may not be the most efficient choice for very large datasets. For such cases, more advanced algorithms like binary search, hash tables, or tree-based structures may offer better performance. Nonetheless, linear search remains a valuable tool in a programmer's arsenal for specific use cases and as a fundamental concept for understanding searching and iteration in computer science.

Advantages:

  • Ease of Implementation: Linear search is one of the simplest search algorithms to understand and implement. Its uncomplicated nature makes it an excellent choice for beginners and for quick problem-solving.
  • Applicability to Unordered Data: Linear search works equally well on both ordered and unordered data. It doesn't require any specific data arrangement, making it versatile for various scenarios.
  • No Preprocessing Required: Unlike many other search algorithms that rely on data structures like sorted arrays or trees, linear search does not require preprocessing of data. You can apply it directly to the dataset, which can be more efficient in cases where data changes frequently.
  • Useful for Small Datasets: In situations with relatively small datasets, linear search can be as fast as or even faster than more complex algorithms. Its constant time complexity (O(1)) for the best-case scenario (the element being at the first position) makes it a competitive choice for small collections.
  • Straightforward Debugging: Debugging and error tracing are easier in linear search due to its simplicity. This makes it a good option for quickly identifying issues in the search process.
  • Diagnostics and Validation: Linear search can be a valuable tool for validating data and performing diagnostics. It helps identify duplicates, missing elements, and other data-related issues.
  • Educational Value: Linear search serves as a foundational concept for understanding more advanced searching algorithms and data structures. It provides a stepping stone for learning more complex algorithms like binary search and hash-based data structures.
  • Resource Efficiency: In situations where you only need to search through a dataset once or very infrequently, the overhead of implementing a more complex search algorithm may not be justified. Linear search is a lean and straightforward option.
  • Control Flow Logic: Linear search can be used for building control flow logic in various programs, helping you make decisions based on the presence or absence of certain elements in a dataset.
  • Dynamic Data: For data structures that frequently change in size, like dynamic arrays or lists, linear search can be used to locate elements efficiently without the need for reorganizing the data structure.

Disadvantages:

  • Inefficient for Large Datasets: Linear search has a time complexity of O(n), where 'n' represents the number of elements in the dataset. This means that the time it takes to find an element increases linearly with the size of the dataset. For very large datasets, the algorithm can be slow and impractical.
  • Worst-Case Scenario: In the worst-case scenario, when the target element is located at the end of the dataset or is not present at all, linear search requires checking every element. This results in the maximum possible execution time.
  • No Benefit from Data Ordering: Linear search does not take advantage of ordered data. Whether the data is sorted or not, it has to examine each element one by one, making it less efficient for ordered datasets where other algorithms like binary search would perform significantly better.
  • Inefficient for Repeated Searches: If you need to search for multiple elements in the same dataset, linear search can become highly inefficient. Other data structures like hash tables or binary search trees are better suited for repetitive searches.
  • Not Suitable for Real-Time Systems: In applications that require real-time responses or very low latency, linear search may not meet the speed requirements. Faster search algorithms are necessary in such cases.
  • Limited Scalability: As the dataset size grows, the time required for a linear search also increases. This limits the scalability of the algorithm and its suitability for large-scale applications.
  • Resource Inefficiency: Linear search may not be the most resource-efficient algorithm in terms of computational power and memory usage for large datasets. More efficient algorithms can utilize resources more effectively.
  • No Benefit from Partial Matches: Linear search can't take advantage of partial matching or fuzzy search techniques. It can only determine if an exact match exists, and if it doesn't, it needs to traverse the entire dataset.
  • Missed Optimization Opportunities: Linear search doesn't benefit from advanced data structures that optimize for specific types of searches. For example, it doesn't make use of tree structures for more efficient search operations.
  • Dependent on Data Arrangement: While it doesn't require data to be sorted, the efficiency of linear search depends on the arrangement of data. In some cases, data may be organized in a way that makes linear search less efficient.

Conclusion:

Linear search, also known as sequential search, is a straightforward and fundamental searching algorithm in computer science. It is a simple method for locating a specific element or data within a dataset, whether that dataset is an array, list, or any linear structure. Linear search iterates through the elements sequentially, comparing each element with the target value until a match is found or the entire dataset has been searched. It is characterized by its simplicity, ease of implementation, and its O(n) time complexity.

Linear search has a variety of applications in real-world scenarios, from searching for items in a list to finding specific data in unsorted datasets. It can be used in various programming languages, including C++, as demonstrated in the examples provided. Although it is not the most efficient searching algorithm for large datasets, it remains an essential concept for beginners in computer science, helping them build a foundational understanding of algorithms and problem-solving techniques.

In summary, linear search may not be the fastest searching method for large or sorted datasets, but it is a valuable tool in a programmer's toolkit, offering simplicity and reliability in cases where data is not organized for more complex search techniques. Understanding linear search is a crucial step in a programmer's journey towards mastering algorithms and data structures.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA