Binary Searching Of Arrays

Another way of searching large arrays in a more effective/efficient way is to do a binary search.

How does this work different that the methods from the Find Elements program?  Those other methods load all of the array elements in memory and then perform searches. As you can imagine this put quite the workload on the computer and possibly have out of memory exceptions depending on your environment.

With a binary search it basically uses an algorithm takes small chunks of the array, loads them in memory, and searches thru that. This method only has a benefit on large arrays. The typical rule is if the array is over 100 elements use this method. Otherwise use the more linear approaches from the other methods.

FindingElementsResults FindingElementsSolution
Program.cs code contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinarySearch
{
    class Program
    {
        ///
<summary>
        /// Demonstrating how to use binary searching for large arrays. 
        /// Take note that this only has a performance gain on very large arrays. 
        /// The example array here is for a reference to see how the methods work only.
        /// </summary>

        /// <param name="args"></param>

        static void Main(string[] args)
        {
            string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

            // To use binary searching the array must be sorted first.
            Array.Sort(daysOfWeek);

            binarySearchArray(daysOfWeek);

            Console.ReadLine();
        }

        private static void binarySearchArray(string[] daysOfWeek)
        {
            int indexOfDay = Array.BinarySearch(daysOfWeek, "Saturday");

            Console.WriteLine("****Binary Searching For Array Element****");
            Console.WriteLine("Array Index: {0}", indexOfDay);
            Console.WriteLine(daysOfWeek[indexOfDay]);
        }
    }
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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