-
Notifications
You must be signed in to change notification settings - Fork 3
/
Interpolation_Search.cs
51 lines (43 loc) · 1.39 KB
/
Interpolation_Search.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
namespace Interpolation_Search
{
class Program
{
public static int interpolation(int[] a, int n, int search_item) // Function implementing Interpolation_Search
{
int high = n - 1;
int low = 0;
int pos;
while(low <= high && search_item >= a[low] && search_item <= a[high])
{
int rise = high - low;
int run = a[high] - a[low];
int x = search_item - a[low];
pos = low + (rise / run) * x;
if(a[pos] == search_item)
return pos;
else if(search_item < a[pos])
high = pos - 1;
else if(search_item > a[pos])
low = pos + 1;
}
return -1;
}
public static void Main(String[] args)
{
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Sorted Input array
int n = a.GetLength(0); // Size of array
int search_item = 8; // Element to be searched
int index = interpolation(a, n, search_item);
if(index == -1)
Console.WriteLine("Element not found");
else
Console.WriteLine("Found at position " + index);
Console.WriteLine();
Console.ReadLine();
}
}
}
/* Output
Found at position 7
*/