Skip to content

Instantly share code, notes, and snippets.

@LindaLawton
Created March 13, 2017 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LindaLawton/ceb121a2f1bfe34db14dac9859a54b4a to your computer and use it in GitHub Desktop.
Save LindaLawton/ceb121a2f1bfe34db14dac9859a54b4a to your computer and use it in GitHub Desktop.
binary search (or binary chop) o(log n) is a Logarithmic algorithm. Doubling the data only means it needs to do one extra chop.
using System;
using System.Linq;
namespace CsharpCodeExamples
{
class Program
{
static void Main(string[] args)
{
// binary search (or binary chop) o(log n) is a Logarithmic algorithm.
// Doubling the data only means it needs to do one extra chop.
int[] data = Enumerable
.Range(0, 120).ToArray();
int find = 11;
int length = data.Length;
Console.WriteLine(string.Format("Array contains '{0}' items.", data.Length - 1));
int low = 0;
int high = data.Length - 1;
var checkCnt = 0;
while (low <= high)
{
checkCnt++;
var mid = (low + high) / 2;
if (find == data[mid])
{
Console.WriteLine(string.Format("{0} can be found at number '{1}'", find, mid));
break;
}
else if (find < data[mid])
high = mid - 1;
else
low = mid + 1;
}
Console.WriteLine(string.Format("I preformed '{0}' checks", checkCnt));
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment