Algorithm - Linear search

A linear search accepts a target value and checks every element of the array to be searched in turn, until either a match is found or the end of the array is reached. The following example looks for a name in an array of names, and if found, retrieves the position of that name in the array:

BEGIN LinearSearch
  Let i = 1
  Let FoundIt = false
  Get RequiredName
  WHILE FoundIt is false AND i <= number of names
    IF Names(i) <> RequiredName THEN
      i = i + 1
    ELSE
      Let FoundIt = true
    ENDIF
  ENDWHILE
  IF FoundIt THEN
    ’note the use of the expression FoundIt (which returns either true or false) rather than the more cumbersome FoundIt = true
      Display “Name found at position ” i
    ELSE
      Display “Required person not found”
    ENDIF
END LinearSearch

To watch how this search works look at http://algorithms.openmymind.net/search/linear.html

To see how this translates into C# code go to http://compileonline.com and paste this code:

using System.IO;
using System;

class Program
{
    static void Main()
    {
        string[] names = new string[] { "Dave", "Joe", "John", "Fred" };
        int numNames = 4;
        int i = 0;
        bool foundIt = false;
        Console.WriteLine("Enter the Search name\n");
        string requiredName = Console.ReadLine();
        while (foundIt == false && i < numNames)
        {
             if (names[i] != requiredName)
            {
                i = i + 1;
            } else {
                foundIt = true;
            }
        }

        if (foundIt)
        {
            Console.WriteLine("Name {0} found at position {1}\n", names[i], i + 1);
            Console.ReadLine(); // keep console open
        } else {
            Console.WriteLine("Name not found");
            Console.ReadLine(); // keep console open
        }
    }
}

Comments

comments powered by Disqus