#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 software development and sailing.

2 Responses 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#

  2. Christopher Wodarczyk says:

    I believe if Find/FindAll fail, they return null for reference types only (their default value)… for value types (int, double, float), they return their default values (0, 0.0, etc)…

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 )

Google photo

You are commenting using your Google 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

%d bloggers like this: