Linear Search Algorithm Implementation in C#

1. Introduction

Linear Search, also known as a sequential search, is a straightforward approach to find a particular element in a list. It checks each element of the list sequentially until a match is found or the whole list has been searched.

2. Implementation Steps

1. Start from the first element of the list.

2. Compare the current element with the target element.

3. If they match, return the current index.

4. If not, move to the next element and repeat step 2.

5. If the end of the list is reached without finding the target, return an indicator that it's not present (often -1).

3. Implementation in C#

using System;
public class LinearSearch {
    // Linear search function
    public static int Search(int[] arr, int x) {
        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] == x)
                return i;
        }
        return -1;
    }
}
public class Program {
    public static void Main() {
        int[] arr = {2, 4, 0, 1, 9};
        int x = 1;
        Console.WriteLine("Array elements:");
        foreach (var item in arr) {
            Console.Write(item + " ");
        }
        int result = LinearSearch.Search(arr, x);
        if (result == -1) {
            Console.WriteLine("\nElement not present in array.");
        } else {
            Console.WriteLine($"\nElement {x} is present at index {result}.");
        }
    }
}

Output:

Array elements:
2 4 0 1 9
Element 1 is present at index 3.

Explanation:

1. LinearSearch is a class containing the logic for the linear search algorithm.

2. The Search function within the LinearSearch class implements the linear search algorithm. It iterates over each element of the array, and if the element matches the target, it returns its index.

3. The Program class contains the Main method that demonstrates how the LinearSearch class can be used to find an element's index in an integer array.

4. If the element is not found in the array, the Search function returns -1, indicating that the element is not present.


Comments