What Is Linear Search in Data Structure With Example?

//

Larry Thompson

Linear search is a basic searching algorithm used to find the position of an element in a given list or array. It scans each element of the list sequentially until it finds a match or reaches the end of the list. In this article, we will explore the concept of linear search in data structure with an example.

How does Linear Search work?

The linear search algorithm starts from the beginning of the list and compares each element with the Target value. If a match is found, it returns the index position of that element. If no match is found after scanning through all elements, it returns -1 to indicate that the Target value is not present in the list.

Example:

Let’s understand how linear search works with an example:

Step 1: Consider a list of numbers: [4, 9, 2, 7, 5]

Step 2: We want to find the position/index of the number 7 in this list.

Step 3: Starting from the first element (4), we compare it with our Target value (7). Since they are not equal, we move on to the next element.

Step 4: Comparing 9 with our Target value (7) again gives us no match.

We continue to iterate through each element.

Step 5: Finally, when we reach the fourth element (7), we find a match. Therefore, we return its index position as 3.

Pseudocode for Linear Search:

Pseudocode:

function linearSearch(list, Target):
    for i in range(0, length(list)):
        if list[i] == Target:
            return i
    return -1

The above pseudocode represents the algorithmic steps involved in linear search. It takes a list and a Target value as parameters and returns the index position of the Target value if found, or -1 if not found.

Advantages and Disadvantages:

Advantages:

  • Linear search is simple to understand and implement.
  • It works well for small-sized lists or arrays.
  • No prior knowledge of the data structure is required.

Disadvantages:

  • Linear search has a time complexity of O(n), where n is the number of elements in the list. This means that as the size of the list increases, the time taken to search also increases linearly.
  • For large-sized lists, other searching algorithms like binary search or hash tables are more efficient.

Conclusion:

In conclusion, linear search is a straightforward searching algorithm that sequentially compares each element in a list or array until it finds a match. While it may not be efficient for large-sized lists, it serves as an excellent starting point for understanding searching algorithms in data structures.

I hope this article has provided you with a clear understanding of what linear search is in data structures with an example. Happy coding!

Discord Server - Web Server - Private Server - DNS Server - Object-Oriented Programming - Scripting - Data Types - Data Structures

Privacy Policy