if (index != -1) Console.WriteLine("数字" + result + "在索引的位置是:" + index); else Console.WriteLine("呜呜," + result + " 在hash中没有找到!");
} }
///<summary> /// Hash表检索数据 ///</summary> ///<param></param> ///<param></param> ///<param></param> ///<returns></returns> static int SearchHash(int[] hash, int hashLength, int key) { //哈希函数 int hashAddress = key % hashLength;
//指定hashAdrress对应值存在但不是关键值,则用开放寻址法解决 while (hash[hashAddress] != 0 && hash[hashAddress] != key) { hashAddress = (++hashAddress) % hashLength; }
//查找到了开放单元,表示查找失败 if (hash[hashAddress] == 0) return -1; return hashAddress;
}
///<summary> ///数据插入Hash表 ///</summary> ///<param>哈希表</param> ///<param></param> ///<param></param> static void InsertHash(int[] hash, int hashLength, int data) { //哈希函数 int hashAddress = data % 13;
//如果key存在,则说明已经被别人占用,此时必须解决冲突 while (hash[hashAddress] != 0) { //用开放寻址法找到 hashAddress = (++hashAddress) % hashLength; }
//将data存入字典中 hash[hashAddress] = data; } } }
结果:
索引查找: 一提到“索引”,估计大家第一反应就是“数据库索引”,对的,其实主键建立“索引”,就是方便我们在海量数据中查找。 关于“索引”的知识,估计大家都比我清楚,我就简单介绍下。 我们自己写算法来实现索引查找时常使用的三个术语: 第一:主表, 这个很简单,要查找的对象。 第二:索引项, 一般我们会用函数将一个主表划分成几个子表,每个子表建立一个索引,这个索引叫做索引项。 第三:索引表, 索引项的集合也就是索引表。
一般“索引项”包含三种内容:index,start,length
第一: index,也就是索引指向主表的关键字。 第二:start, 也就是index在主表中的位置。 第三:length, 也就是子表的区间长度。
复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace IndexSearchProgram { class Program { ///<summary> /// 索引项实体 ///</summary> class IndexItem { //对应主表的值 public int index; //主表记录区间段的开始位置 public int start; //主表记录区间段的长度 public int length; }
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|