Linear Search Algorithm using C#

Linear search, also known as sequential search, is the most simplest and least performance searching algorithm. Literally, It checks every element in the list sequentially until the desired element is found or until all the elements have been searched.

Think of it as finding a contact number in your phone. You starts searching from starting in the list and scrolls till desired contact is not found(if search feature is not available).

Time Complexity:

Linear search is less efficient than binary search because in order to find the element in the worst case the it will have to examine every single item in the array.  The computational complexity for linear search is O(n). 

 

 Linear Search Pseudo Code
  • Starts from left elements of the list and one by one compare the element we are searching for with each element of the list.
  • If found the desired element, return the index.
  • If not found after full scanning of the list, return -1.
C# Implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using System;
 
public class Program
{
	public static void Main()
	{
	    Console.WriteLine("------ Linear Search ------");
            int[] array = { 6, 55, 5, 3, 7, 2, 9, 4, 8, 10 };
            Console.Write("Enter The Number To Search:");
            String input = Console.ReadLine();
            int itemSearch = Convert.ToInt32(input);
            int index = LinearSearch(array, itemSearch);
            if (index != -1)
            {
                Console.WriteLine("Number :" + itemSearch + " found in array at index=" + index);
            }
            else
            {
                Console.WriteLine("Number :" + itemSearch + " not found in array");
            }
	}
 
	public static int LinearSearch(int[] Arr, int item)
        {
            int index = -1;
            for (int i = 0; i < Arr.Length; i++)
            {
                if (Arr[i] == item)
                {
                    index = i;
                    break;
                }
            }
            return index;
        }
}

Try Out

Although, Linear Search is not an efficient search algorithm for search. Its important to understand when it comes to algorithms. In upcoming posts of this series, I will read another efficient searching algorithms called binary search.

So, it was all about Linear Search Algorithm, if you have any query then please comment below and let us know. If you liked this article, then please follow us on Facebook to get notification for new posts.

Happy Learning 🙂

Rahul is a Data Geek, technology enthusiast, a passionate writer, thinker with passion for computer programming.  He loves to explore technology and finds ultimate joy when writing about trending technology, geek stuff and web development.