经典算法之查找

来源:互联网 发布:游戏编程师工资高吗 编辑:程序博客网 时间:2024/05/22 13:58

二分查找

 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                 //如果中间值大于key16                 if (list[middle] > key)17                     high = middle - 1;18                 else19                     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
原创粉丝点击