· Chuck Conway · Programming  · 1 min read

A Binary Search Implementation

The binary search algorithm quickly searches a large array of numbers, it’s often referred to as divide and conquer.

The binary search algorithm quickly searches a large array of numbers, it’s often referred to as divide and conquer.

The binary search algorithm quickly searches a large array of numbers, it’s often referred to as divide and conquer.

public class BinarySearch
{
    public int BinarySearch(int[] items, int searchValue)
    {
        int left = 0;
        int right = items.Length - 1;

        while (left <= right)
        {
            var middle = (left + right) / 2;

            //If the searchValue is in the center, we found it!
            if(items[middle] == searchValue)
            {
                return middle;
            }            

            //If the searchValue is less than the current middle, we set the right to (middle - 1)
            //Because the searchValue is in the lower half of the items.
            if(searchValue < items[middle])
            {
                right = middle - 1;    
            }
            //If the searchValue is greater than the current middle, we set the right to (middle + 1)
            //Because the searchValue is in the higher half of the items.
            else
            {
                left = middle + 1;
            }

        } // now that we've either found the item and returned it or we've reset our search boundaries
          // we'll search it again.

        // Not found.
        return -1;
    }
}
Share:
Back to Blog

Related Posts

View All Posts »
C# 8 - Nullable Reference Types

C# 8 - Nullable Reference Types

Microsoft is adding a new feature to C# 8 called Nullable Reference Types. Which at first, is confusing because all reference types are nullable… so how this different? Going forward, if the feature is enabled, references types are non-nullable, unless you explicitly notate them as nullable.

9 Guidelines for Creating Expressive Names

9 Guidelines for Creating Expressive Names

Naming is subjective and situational, it’s an art, and with most art, we discover patterns. I’ve learned a lot through the reading of other’s code. In this article, I’ve compiled 9 guidelines I wished others had followed when I read their code.

NVarchar Vs Varchar

NVarchar Vs Varchar

Each engineer defining a new string column decides: Do I use nvarchar or do I use varchar?