Friday, July 30, 2010
 
   
 
Welcome to my site

First let me say thanks for stopping by my site. My name is David Hanson-Graville and I am a IT consultant working in the UK. Let me make it clear, I am passionate about technology and specifically .net and its various forms. I've programmed in a range of langages, but I can say, I am now at my happiest when coding with c#. I hope my blog is an enjoyable & educational read and please feel free to email me at David.Hanson@OnTheBlog.net if you have any questions. 

C# Binary Search Minimize
Location: BlogsOnTheBlog    
Posted by: David Hanson Mon, 07 Apr 2008 12:50:37 GMT

A binary search is an algorithm is able to find a specific value within a sorted array by making increasingly acurate guesses based on a comparision result. I was discussing this with a friend at work the other day and thought I would put one together in C# for illustrative purposes. 

First we need to create the array with random data and then sort this array. I decided that using guids would provide a good level of random data for our test. I therefore create a million guids in my array then sort it. This is shown below.

        ///
        /// Mains the specified args.
        ///
        /// The args.
        static void Main(string[] args)
        {
 
            //Setup random data.
            List<String> RandomItems = new List<string>();
            for (int i = 0; i < 1000000; i++){RandomItems.Add(Guid.NewGuid().ToString());}
            //Get search item and sort.
            string searchFor = RandomItems[345];
            RandomItems.Sort();
            Console.WriteLine("Press enter to run test");
            Console.ReadLine();
         }

Next I created the algorithm which would quickly narrow down on the value we are searching for. There are 3 things to remember when it comes to binary searches.

  1. Find the median of a particular range within your array.
  2. Compare the value at that midpoint to see if ths greaterthan, lessthan or Equal.
  3. Call the same method recursively in order to narrow the search.

The Binary search class is shown below.

        ///
        /// Finds the index. (Public Overload.)
        ///
        ///
        /// The sorted list.
        /// The search criteria.
        ///The index of the specified item.
        public static int FindIndex(List<String> sortedList,string searchCriteria)
        {
            return FindIndex(sortedList, searchCriteria, 0,sortedList.Count);
        }
 
        ///
        /// Finds the index.
        ///
        /// The sorted list.
        /// The search criteria.
        /// The startposition.
        ///The index of the specified
        private static int FindIndex(List<string> sortedList,string searchCriteria, int startPosition, int endPosition)
        {
            int lastPos = startPosition;
            int range = (endPosition - startPosition);
            if (range == 0) return 0;
            int midPoint = (range / 2) + startPosition;
            int equality = sortedList[midPoint].CompareTo(searchCriteria);
 
            Console.WriteLine(midPoint);
            //Equals
            if (equality == 0)
                return midPoint;
            //Greater than
            if (equality == -1)
                return FindIndex(sortedList, searchCriteria, midPoint, endPosition);
            //Less than
            if (equality == 1)
                return FindIndex(sortedList, searchCriteria, lastPos, midPoint);
 
            return -1;
    
        }

 Finally, I want to run the algorithm and work out the cost of finding my value within a million strings. So we need to add the following to our static main.

//Run our binary search.
DateTime start = DateTime.Now;
Console.WriteLine("Item found at position [" + BinarySearch.FindIndex(RandomItems, searchFor).ToString() + "]");
DateTime end = DateTime.Now;
Console.WriteLine("Cost M/s: " + new TimeSpan(end.Ticks - start.Ticks).TotalMilliseconds.ToString());
Console.ReadLine();

 The results of running this algorithm are shown here.

Press enter to run test
 
500000
250000
375000
312500
343750
328125
335937
332031
330078
329101
329589
329833
329955
330016
329985
330000
330008
330012
330014
330013
Item found at position [330013]
Cost M/s: 5
Permalink |  Trackback

Comments (3)   Add Comment
Re: C# Binary Search    By Mike Park on Wed, 16 Apr 2008 08:13:40 GMT
5 milliseconds. Not bad!

Re: C# Binary Search    By Miroslav Spassov on Fri, 03 Oct 2008 08:09:24 GMT
Your code is flawed. It will result in Stack Overflow Exception if you try to search for value which doesn't exist in the collection.<br>I think that you should change : if (range == 0) return 0; to<br>if(range < 2) return -1; It worked this way for me.

Re: C# Binary Search    By host on Fri, 03 Oct 2008 08:11:39 GMT
Miroslav, your correct. For the sake of the post I had assumed you would be searching for a value in the list.<br><br>A fatal mistake it seems. :-)


Your name:
Title:
Comment:
Security Code
Enter the code shown above in the box below
Add Comment   Cancel 
Tweets Minimize
Twitter / LordHanson
  1. LordHanson: Flash on iPad....nice. http://www.tipb.com/2010/07/04/frash-android-flash-ported-ipad/

    Published Sun, 04 Jul 2010 22:07:55 +0000 by
  2. LordHanson: Anyone noticed that when typing on your iPhone it sounds like your holding a gieger counter?

    Published Sun, 04 Jul 2010 22:05:28 +0000 by
  3. LordHanson: Missing wacko's music... What's happened to the album he was working on before he died?

    Published Fri, 25 Jun 2010 23:01:45 +0000 by
  4. LordHanson: New version of Connectify cannot recognise my active Internet connection! Had to roll back to previous version! #fail

    Published Fri, 25 Jun 2010 22:54:54 +0000 by
  5. LordHanson: vuvuzela blowing spoils the world cup! Fact!

    Published Mon, 14 Jun 2010 05:08:43 +0000 by
  6. LordHanson: About http://www.theaustralian.com.au/business/news/us-competition-regulators-to-investigate-apple/story-e6frg90x-1225878779986

    Published Mon, 14 Jun 2010 00:04:45 +0000 by
  7. LordHanson: In the camper van and a storm is coming.....How exciting.

    Published Sun, 25 Apr 2010 04:39:48 +0000 by
  8. LordHanson: My vaio p is doing well while travelling. 3g Internet, HD movies, digital tv, photo editing, wifi router for iPods and much more. Love it

    Published Wed, 10 Mar 2010 10:29:19 +0000 by
  9. LordHanson: Ok so I need to stay techie while away from a computer for a year. Anyone got any ideas.

    Published Mon, 22 Feb 2010 12:31:09 +0000 by
  10. LordHanson: Sitting in YHA Glebe Sydney waiting for the movie night to start

    Published Thu, 18 Feb 2010 08:13:10 +0000 by
  11. LordHanson: I finished work today in prep for travelling. I must admit as i left the office i felt a little emotional. Sign of a good job with great ...

    Published Tue, 26 Jan 2010 17:48:49 +0000 by
  12. LordHanson: Lots of sick sounding people creeping onto the trains today. Stay away stay away!

    Published Fri, 22 Jan 2010 08:14:36 +0000 by
  13. LordHanson: LMAO RT @colmbrophy: so have you seen who owns http://wwwbing.com ? it's not microsoft

    Published Tue, 19 Jan 2010 17:35:43 +0000 by
  14. LordHanson: RT @TeemuHyn: RT @eldarmurtazin: Hate Windows Mobile 7. No apps from previous versions of WM working here. Not compatible at all.

    Published Sun, 17 Jan 2010 19:01:29 +0000 by
  15. LordHanson: The girlfriend has gone all science on me.... She has her head in books about quasars!

    Published Sat, 16 Jan 2010 16:38:58 +0000 by
  16. LordHanson: New blog post: Invoking generic methods with Expression.Call http://bit.ly/5g99Ih

    Published Sat, 16 Jan 2010 16:34:00 +0000 by
  17. LordHanson: Found a nice way to invoke generic methods using expression trees and importantly avoiding Type.Getmethods() which you normally have to do!

    Published Fri, 15 Jan 2010 18:55:38 +0000 by
  18. LordHanson: Tried a dummy run of packing my backpack last night. Just managed to get it all in. The sleeping bag takes half the space. Not good.

    Published Fri, 15 Jan 2010 08:28:47 +0000 by
  19. LordHanson: Why do we get headaches for no apparent reason?

    Published Tue, 12 Jan 2010 15:28:29 +0000 by
  20. LordHanson: @swhelband beer time my friend

    Published Sun, 10 Jan 2010 21:49:44 +0000 by
Print  
Archive Minimize
Print  
Contact me Minimize
Print  
Microsoft Certs Minimize







Print  
Silverlight News Minimize
Silverlight - Google News
  1. Top 10 Things I Wish I Knew Before I Started My Silverlight 4 Project - Redmond Developer News

    Published Thu, 29 Jul 2010 23:21:01 GMT+00:00 by
  2. Microsoft's Flash challenger Silverlight hits Symbian - Register

    Published Tue, 06 Jul 2010 18:54:39 GMT+00:00 by
  3. Windows Phone 7 misses big-business support tools - Register

    Published Mon, 26 Jul 2010 20:32:23 GMT+00:00 by
  4. Neustar Reports Q2 Results, Stock Repurchase - TMCnet

    Published Fri, 30 Jul 2010 13:13:57 GMT+00:00 by
  5. Intertainment begins commercial rollout of Ad Taffy - PR Newswire (press release)

    Published Fri, 30 Jul 2010 14:19:22 GMT+00:00 by
  6. Download Microsoft Expression Studio Ultimate 4.0.20525.0 Free Trial / Full ... - Soft Sailor (blog)

    Published Fri, 30 Jul 2010 08:50:54 GMT+00:00 by
  7. Managing change in the application portfolio - Register

    Published Thu, 29 Jul 2010 09:36:57 GMT+00:00 by
  8. Queen Victoria in Liverpool panoramic picture - Liverpool Echo

    Published Mon, 26 Jul 2010 11:56:30 GMT+00:00 by
  9. AEBN's Silverlight Player Gains Traction with Users - AVN News (press release)

    Published Tue, 27 Jul 2010 20:28:37 GMT+00:00 by
  10. Written by David Conrad - iProgrammer

    Published Tue, 27 Jul 2010 12:39:37 GMT+00:00 by
Print