Binary Search int array - CSharp System

CSharp examples for System:Array Search

Description

Binary Search int array

Demo Code

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using System.Diagnostics;
using System;/*  w w  w  .  java2  s.  c  om*/

public class Main{
        // same as Array.BinarySearch, but without using IComparer to compare ints
        internal static int BinarySearch(this int[] array, int value)
        {
            var low = 0;
            var high = array.Length - 1;

            while (low <= high)
            {
                var middle = low + ((high - low) >> 1);
                var midValue = array[middle];

                if (midValue == value)
                {
                    return middle;
                }
                else if (midValue > value)
                {
                    high = middle - 1;
                }
                else
                {
                    low = middle + 1;
                }
            }

            return ~low;
        }
}

Related Tutorials