经典算法之查找

二分查找

 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     }

 

posted @ 2013-01-28 21:15  binfire005  阅读(523)  评论(0编辑  收藏  举报