#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"));
        }

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. Pingback: #151 – Determining Whether an Array Contains a Specific Element « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers