zoukankan      html  css  js  c++  java
  • 经典算法之查找

    二分查找

     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     }
  • 相关阅读:
    Monggodb基础
    手游运营数据指标
    JSON语法
    Java中日期转换问题
    Java线程中锁的问题
    鼠标移动监听的注意事项
    链接数据库的问题
    获取显示器的宽高
    JTable的使用问题
    JScrollPane控件中添加其他控件的问题&&JScrollPane设置滚动条&&调整滚动速度
  • 原文地址:https://www.cnblogs.com/binfire/p/2880539.html
Copyright © 2011-2022 走看看