Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Last active August 18, 2017 12:07
Show Gist options
  • Save bgadrian/9e1b367b27a75dc6ba06bc7a027463a3 to your computer and use it in GitHub Desktop.
Save bgadrian/9e1b367b27a75dc6ba06bc7a027463a3 to your computer and use it in GitHub Desktop.
Interpolation search (binary search upgraded)
using System;
namespace interpolation
{
class Program
{
//usage: dotnet run 1 2 3 4 7 10 13
static void Main(string[] args)
{
//pseudocode https://www.tutorialspoint.com/data_structures_algorithms/interpolation_search_algorithm.htm
//O worst: n, best case: log(log(n))
Console.WriteLine("Hello World!" + String.Join(",", args));
int[] arr = new int[args.Length];
for (int i = 0; i < args.Length; i++)
{
arr[i] = Int32.Parse(args[i]);
}
if (arr.Length == 0)
arr = new int[4]{
2,3,7,9
};
int lower = 0;
int upper = Math.Max(0, arr.Length - 1);
int mid = -1;
int x = 7;
int found = -1;
while (lower != upper && arr[lower] != arr[upper])
{
mid = lower + (
(upper - lower) / (arr[upper] - arr[lower]) * (x - arr[lower])
);
if (arr[mid] == x)
{
found = mid;
break;
}
if (arr[mid] < x)
{
lower = mid + 1;
} else if (arr[mid] > x){
upper = mid - 1;
}
}
Console.WriteLine("index of " + x + " is " + found);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment