一、二分法
public class BinarySearch
{
public static int Search(List<int> list,int key)
{
int low = 0;
int high = list.Count - 1;
while (low <= high)
{
var middle = (low + high) / 2;
if (list[middle] == key)
return middle;
//如果中间值大于key
if (list[middle] > key)
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
}
二、
哈希查找
/// <summary>
/// 哈希函数
/// </summary>
public class HashSearch
{
static void InsertHash(int[] hash, int hashLength, int data)
{
//哈希函数
int hashAddress = data % 13;
//如果key存在,则说明已经被占用,此时必须解决冲突
while (hash[hashAddress] != 0)
{
//用开放寻址法找到
hashAddress = (++hashAddress) % hashLength;
}
hash[hashAddress] = data;
}
static int SearchHash(int[] hash, int hashLengh, int key)
{
//哈希函数
int hashAddress = key % hashLengh;
while (hash[hashAddress] != 0 && hash[hashAddress] != key)
{
hashAddress = (++hashAddress) % hashLengh;
}
if (hash[hashAddress] == 0)
return -1;
return hashAddress;
}
}