经典算法之查找

二分查找

 1   public class BinarySearch
 2     {
 3         public static int Search(List<int> list,int key)
 4         {
 5             int low = 0;
 6             int high = list.Count - 1;
 7 
 8             while (low <= high)
 9             {
10                 var middle = (low + high) / 2;
11                 
12                 if (list[middle] == key)
13                     return middle;
14 
15                 //如果中间值大于key
16                 if (list[middle] > key)
17                     high = middle - 1;
18                 else
19                     low = middle + 1;
20             }
21             return -1;
22         }
23     }

二:哈希查找

 1   /// <summary>
 2     /// 哈希函数
 3     /// </summary>
 4     public class HashSearch
 5     {
 6         static void InsertHash(int[] hash, int hashLength, int data)
 7         {   
 8             //哈希函数
 9             int hashAddress = data % 13;
10 
11             //如果key存在,则说明已经被占用,此时必须解决冲突
12             while (hash[hashAddress] != 0)
13             {   
14                 //用开放寻址法找到
15                 hashAddress = (++hashAddress) % hashLength;
16             }
17             hash[hashAddress] = data;
18         }
19 
20         static int SearchHash(int[] hash, int hashLengh, int key)
21         {   
22             //哈希函数
23             int hashAddress = key % hashLengh;
24 
25             while (hash[hashAddress] != 0 && hash[hashAddress] != key)
26             {
27                 hashAddress = (++hashAddress) % hashLengh;
28             }
29             if (hash[hashAddress] == 0)
30                 return -1;
31             return hashAddress;
32         }
33     }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值