#145 – Using Array.Find to Search an Unsorted Array

You can use Array.BinarySearch to search a sorted array taking O(log n) time, but if you have an unsorted array, you can search it in O(n) time using the Array.Find method.

The Find method takes an array to search and a function that knows how to look for a match.  This matching function accepts a single element of the array and returns true or false, depending on whether a match is found.

Find returns a reference to the object in the array, or null if a match is not found.

        static void Main(string[] args)
        {
            Person[] folks = new Person[4];
            folks[0] = new Person("Bronte", "Emily");
            folks[1] = new Person("Bronte", "Charlotte");
            folks[2] = new Person("Tennyson", "Alfred");
            folks[3] = new Person("Mailer", "Norman");

            Person thereHeIs = (Person)Array.Find(folks, FindNorman);
            folks[3].LastName = "Mailman";
        }

        static bool FindNorman(Person p)
        {
            return ((p.FirstName == "Norman") && (p.LastName == "Mailer"));
        }