C# Program to Implement Linear Search

C# Program to Implement Linear Search

Searching is one of the most fundamental tasks in programming. When we need to find an element in a dataset, understanding basic search algorithms is crucial. Linear Search is the simplest searching algorithm, where we check each element in the list or array one by one until we find the target. It’s easy to understand and implement, which makes it perfect for beginners learning the basics of searching.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Linear Search is used when the dataset is small or unsorted, where advanced algorithms like Binary Search cannot be applied. It is straightforward but not the most efficient for large datasets. Despite this, learning Linear Search helps build a foundation for understanding more complex searching algorithms and prepares beginners to handle real-world problems where data might be unordered.

Program 1: Linear Search Using Loop

This program demonstrates the most common approach to Linear Search using a simple loop. It checks each element of the array sequentially and stops when the target is found.

using System;

class Program
{

    static void Main()
    {

        int[] numbers = { 10, 20, 30, 40, 50 };
        int target = 30;
        bool found = false;

        for (int i = 0; i < numbers.Length; i++)
        {

            if (numbers[i] == target)
            {

                Console.WriteLine($"Element {target} found at index {i}");

                found = true;
                break;

            }

        }

        if (!found)
            Console.WriteLine($"Element {target} not found in the array");

    }

}

In this example, the program loops through the array and compares each element with the target. If a match is found, it prints the index. This approach is easy to understand and ideal for beginners learning how to iterate through arrays.

Program 2: Linear Search Using a Method

Here, we separate the search logic into a reusable method, making the program cleaner and more modular.

using System;

class Program
{

    static int LinearSearch(int[] arr, int key)
    {

        for (int i = 0; i < arr.Length; i++)
        {

            if (arr[i] == key)
                return i;

        }

        return -1;

    }

    static void Main()
    {

        int[] numbers = { 5, 15, 25, 35, 45 };
        int target = 25;

        int result = LinearSearch(numbers, target);

        if (result != -1)
            Console.WriteLine($"Element {target} found at index {result}");
        else
            Console.WriteLine($"Element {target} not found in the array");

    }

}

Using a method allows beginners to reuse the search function in multiple programs or arrays without rewriting code. It also helps in understanding return values and modular programming.

Program 3: Linear Search Using Recursion

This version uses recursion to perform Linear Search. It checks one element at a time and then calls itself for the remaining array.

using System;

class Program
{

    static int LinearSearchRecursive(int[] arr, int key, int index)
    {

        if (index >= arr.Length)
            return -1;

        if (arr[index] == key)
            return index;

        return LinearSearchRecursive(arr, key, index + 1);

    }

    static void Main()
    {

        int[] numbers = { 2, 4, 6, 8, 10 };
        int target = 8;

        int result = LinearSearchRecursive(numbers, target, 0);

        if (result != -1)
            Console.WriteLine($"Element {target} found at index {result}");
        else
            Console.WriteLine($"Element {target} not found in the array");

    }

}

Recursion is a different way to approach problems. It may not be as efficient as loops for large arrays, but it helps beginners understand recursive thinking and function calls.

Program 4: Linear Search for Strings

Linear Search can be applied to strings as well. This program demonstrates searching for a string in an array of names.

using System;

class Program
{

    static void Main()
    {

        string[] names = { "Harry", "Hermione", "Ron", "Ginny" };
        string target = "Ron";
        bool found = false;

        for (int i = 0; i < names.Length; i++)
        {

            if (names[i] == target)
            {

                Console.WriteLine($"Name {target} found at index {i}");

                found = true;
                break;

            }

        }

        if (!found)
            Console.WriteLine($"Name {target} not found in the array");

    }

}

This shows how Linear Search is versatile and can be used for different data types, not just numbers. Beginners can easily adapt this approach for arrays of strings, characters, or other simple objects.

Frequently Asked Questions (FAQ)

Q1: What is the time complexity of Linear Search?
The time complexity is O(n), where n is the number of elements in the array. It checks each element sequentially.

Q2: Is Linear Search efficient for large datasets?
No, Linear Search is simple but not efficient for very large datasets. Algorithms like Binary Search are better for sorted arrays.

Q3: Can Linear Search work on unsorted arrays?
Yes, Linear Search works perfectly on unsorted arrays, unlike Binary Search, which requires a sorted array.

Q4: Is Linear Search stable?
Yes, Linear Search is stable because it finds elements without changing the order of other elements.

Conclusion

Linear Search is the most basic and beginner-friendly searching algorithm in C#. It helps beginners understand how to iterate through arrays, compare elements, and use both loops and recursion. Although it is not the fastest method for large datasets, it is simple, versatile, and a great stepping stone to more advanced searching techniques. Practicing Linear Search on numbers, strings, and other data types builds a strong foundation for learning algorithms and problem-solving in C#.

Once comfortable with Linear Search, you can explore Binary Search, Interpolation Search, and other advanced algorithms to improve efficiency and handle larger datasets.

Scroll to Top