allizwell.jobsdoor360.in

Linear Search

Data Structures and Algorithms / Searching and Sorting / Linear Search

Linear Search in Data Structures and Algorithms

Linear Search is one of the simplest searching algorithms in Data Structures and Algorithms. It finds a target element by checking each element of an array or list one by one, starting from the first element. It works on both sorted and unsorted data and is especially useful when the dataset is small or elements are not arranged in any particular order.

1. What is Linear Search?

Linear Search is a searching technique in which every element of a collection is checked sequentially until the required element is found or all elements have been examined.

It starts from the first element and compares it with the target value. If the current element matches the target, the search is successful. Otherwise, the algorithm moves to the next element.

If the target element is not present in the collection, Linear Search checks every element and returns an appropriate result indicating that the element was not found.

Example

Consider the following array:

arr = [10, 25, 30, 45, 50]

Suppose we want to search for:

target = 45

The algorithm compares the target with each element:

  • Compare 45 with 10: Not equal.
  • Compare 45 with 25: Not equal.
  • Compare 45 with 30: Not equal.
  • Compare 45 with 45: Element found.

Therefore, the element 45 is found at index 3.

2. How Does Linear Search Work?

Linear Search follows a straightforward process. It examines elements one after another until it finds the required value or reaches the end of the collection.

Step-by-Step Process

  1. Start from the first element of the array.
  2. Compare the current element with the target value.
  3. If both values are equal, return the current index.
  4. If they are not equal, move to the next element.
  5. Repeat the comparison for every element.
  6. If the end of the array is reached without finding the target, return -1.
Important: Linear Search does not require the array to be sorted. It can search for an element in both sorted and unsorted arrays.

3. Linear Search Algorithm

The following pseudocode describes the basic working of Linear Search:

LinearSearch(arr, n, target):

    for i = 0 to n - 1:

        if arr[i] == target:
            return i

    return -1

Explanation:

  • arr represents the input array.
  • n represents the number of elements.
  • target is the value to search for.
  • The loop checks every element from index 0 to n - 1.
  • If the target is found, its index is returned.
  • If no match is found, the function returns -1.

4. Linear Search Implementation in C++

Let us implement Linear Search using a C++ function. The function accepts an array, its size, and the target element. It returns the index if the element is found.

#include <iostream>
using namespace std;

int linearSearch(int arr[], int n, int target) {

    for (int i = 0; i < n; i++) {

        if (arr[i] == target) {
            return i;
        }
    }

    return -1;
}

int main() {

    int arr[] = {10, 25, 30, 45, 50};

    int n = sizeof(arr) / sizeof(arr[0]);

    int target = 45;

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

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

    return 0;
}

Output

Element found at index: 3

5. Understanding the C++ Code

Step 1: Define the Search Function

int linearSearch(int arr[], int n, int target)

This function receives three arguments:

  • The array in which we want to search.
  • The number of elements in the array.
  • The target value that we want to find.

It returns an integer representing the index of the target element or -1 if the element is not found.

Step 2: Traverse the Array

for (int i = 0; i < n; i++)

The loop starts from index 0 and continues until the last valid index of the array. This allows us to examine every element sequentially.

Step 3: Compare the Element

if (arr[i] == target)

At every iteration, the current array element is compared with the target value.

Step 4: Return the Index

return i;

If the current element matches the target, the function immediately returns its index. There is no need to continue searching.

Step 5: Return -1 if Not Found

return -1;

If the loop finishes without finding the target, the function returns -1. This indicates that the requested element does not exist in the array.

6. Dry Run of Linear Search

A dry run means executing an algorithm manually to understand how its values change at every step.

Consider the following array:

arr = [12, 25, 37, 48, 59, 65]

Target element:

target = 48

Let us examine each comparison:

Step Index Current Element Comparison Result
1 0 12 12 == 48 Not Found
2 1 25 25 == 48 Not Found
3 2 37 37 == 48 Not Found
4 3 48 48 == 48 Found

The search stops when the target is found.

Element found at index: 3

7. Linear Search When the Element Is Not Found

Consider an array in which the target element does not exist. Linear Search must examine every element before concluding that the target is absent.

arr = [10, 20, 30, 40, 50]
target = 60

Comparisons:

Index Array Element Comparison with 60 Result
0 10 10 == 60 Not Found
1 20 20 == 60 Not Found
2 30 30 == 60 Not Found
3 40 40 == 60 Not Found
4 50 50 == 60 Not Found

Element not found

When an element is absent, Linear Search performs n comparisons for an array containing n elements.

8. Linear Search with Multiple Occurrences

Sometimes the same element appears more than once in an array. The basic Linear Search implementation returns the index of the first occurrence because it stops immediately after finding a match.

Consider this array:

arr = [10, 20, 30, 20, 40, 20]

Target:

target = 20

The first occurrence is at index 1. To find every occurrence, we must continue searching instead of returning immediately.

C++ Code to Find All Occurrences

#include <iostream>
using namespace std;

int main() {

    int arr[] = {10, 20, 30, 20, 40, 20};

    int n = sizeof(arr) / sizeof(arr[0]);

    int target = 20;

    bool found = false;

    cout << "Element found at indexes: ";

    for (int i = 0; i < n; i++) {

        if (arr[i] == target) {

            cout << i << " ";

            found = true;
        }
    }

    if (!found) {
        cout << "Not found";
    }

    return 0;
}

Output

Element found at indexes: 1 3 5

9. Linear Search in a String

Linear Search can also be used to search for a character inside a string. Each character is checked sequentially until the required character is found.

C++ Example

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

int main() {

    string str = "programming";

    char target = 'm';

    int result = -1;

    for (int i = 0; i < str.length(); i++) {

        if (str[i] == target) {

            result = i;
            break;
        }
    }

    if (result != -1) {
        cout << "Character found at index: " << result;
    }
    else {
        cout << "Character not found";
    }

    return 0;
}

Output

Character found at index: 6

The character 'm' first appears at index 6 in the string "programming".

10. Time Complexity of Linear Search

Time complexity describes how the number of operations performed by an algorithm changes as the input size grows.

Linear Search has different time complexities depending on the position of the target element.

Case Condition Comparisons Time Complexity
Best Case Target is the first element 1 O(1)
Average Case Target is somewhere in the array Approximately (n + 1) / 2 O(n)
Worst Case Target is last or not present n O(n)

Best Case: O(1)

The best case occurs when the target element is present at the first position. Only one comparison is required.

Average Case: O(n)

On average, the algorithm examines approximately half of the elements before finding the target, assuming each position is equally likely to contain it.

Worst Case: O(n)

The worst case occurs when the target is at the last position or does not exist in the array. Every element must be checked.

Remember: The overall worst-case time complexity of Linear Search is O(n), where n is the number of elements.

11. Space Complexity of Linear Search

Space complexity describes the additional memory required by an algorithm while it executes.

The iterative Linear Search algorithm uses only a few variables, such as:

  • Loop variable i.
  • Target value.
  • Array size.
  • Return value.

It does not create another array or use memory that grows with the input size.

Auxiliary Space Complexity: O(1)

12. Advantages of Linear Search

  • Very easy to understand and implement.
  • Works with sorted and unsorted arrays.
  • Does not require additional memory.
  • Can be used with arrays, lists, and strings.
  • Useful for small datasets.
  • Does not require any preprocessing or sorting.

13. Disadvantages of Linear Search

  • It can be slow for very large datasets.
  • It may need to examine every element.
  • Its worst-case time complexity is O(n).
  • It is less efficient than Binary Search for suitable sorted data.
  • Repeated searches over a large collection can require many comparisons.

14. Linear Search vs Binary Search

Linear Search and Binary Search are two commonly used searching algorithms. Both find elements in a collection, but their working methods and efficiency are different.

Feature Linear Search Binary Search
Approach Checks elements one by one Repeatedly divides the search range in half
Data Requirement Works on sorted and unsorted data Requires sorted data
Best Case O(1) O(1)
Average Case O(n) O(log n)
Worst Case O(n) O(log n)
Auxiliary Space O(1) O(1) for iterative implementation
Implementation Simple Requires careful boundary handling

15. Applications of Linear Search

Linear Search is useful in situations where the dataset is small, unsorted, or accessed sequentially.

  • Small Arrays: Searching for values in small collections of data.
  • Student Records: Finding a particular student in a small list of records.
  • Inventory Systems: Checking whether a product exists in a small inventory list.
  • String Processing: Finding a character in a string.
  • Unsorted Data: Searching when elements are not arranged in sorted order.
  • Simple Applications: Implementing basic search functionality without preprocessing.

16. Common Mistakes to Avoid

  • Starting the loop from index 1 instead of index 0.
  • Using i <= n instead of i < n, which can access an invalid index.
  • Forgetting to return -1 when the target is not found.
  • Confusing an array index with the element's value.
  • Returning immediately when the task requires finding all occurrences.
  • Assuming that Linear Search requires sorted data.
  • Ignoring the possibility of duplicate elements.

17. Practice Questions

Basic Questions

  1. What is Linear Search?
  2. How does Linear Search work?
  3. Does Linear Search require a sorted array?
  4. What does the function return when an element is not found?
  5. What is the best-case time complexity of Linear Search?

Intermediate Questions

  1. Find the index of 35 in the array [10, 20, 35, 40, 50].
  2. How many comparisons are required to find 70 in [10, 20, 30, 40, 50, 60, 70]?
  3. What happens when the target element appears multiple times?
  4. Explain the best, average, and worst cases of Linear Search.
  5. Compare Linear Search and Binary Search.

Programming Practice

  1. Write a C++ program to search for an element in an array using Linear Search.
  2. Write a program to find all occurrences of a target element.
  3. Write a program to search for a character in a string.
  4. Write a program to count the number of occurrences of an element.
  5. Write a program to find the first and last occurrence of a given element using Linear Search.

18. Key Takeaways

  • Linear Search checks elements sequentially, one by one.
  • It works with both sorted and unsorted data.
  • It returns the index when the target is found.
  • It returns -1 when the target is absent.
  • Its best-case time complexity is O(1).
  • Its average and worst-case time complexity are O(n).
  • Its auxiliary space complexity is O(1).
  • It is simple and useful for small datasets.
Next Topic: In the next lesson, we will learn Binary Search, an efficient searching algorithm that repeatedly divides a sorted search range into two halves.
Scroll to Top