为了是关键字都可以存储在指定大小的数组中"使用
public int hashFunc(int key)
{
return key % arraySize; // hash function
}
对关键字进行hash'
线性探测
查找: 如果hashFunc之后的值中无数据 直接返回 有数据 就线性到下一个 如果下一个是空的 就插入 否则继续
public DataItem find(int key) // find item with key
{
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{ // found the key?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // yes, return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
}
return null; // can't find item
}
删除:如果hashFunc后的有数据 就删除 没有就线性到下一个 知道找到有那个数据的 把数据删除并把这个空间置为 -1 否则返回没有找到
public DataItem delete(int key) // delete a DataItem
{
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{ // found the key?
if(hashArray[hashVal].getKey() == key)
{
DataItem temp = hashArray[hashVal]; // save item
hashArray[hashVal] = nonItem; // delete item
return temp; // return item
}
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
}
return null; // can't find item
} // end delete()
插入:如果hashFunc后 对于的数组空间有空就插入 没有就线性到下一个知道找到空白并插入
public void insert(DataItem item) // insert a DataItem
// (assumes table not full)
{
int key = item.getKey(); // extract key
int hashVal = hashFunc(key); // hash the key
// until empty cell or -1,
while(hashArray[hashVal] != null &&
hashArray[hashVal].getKey() != -1)
{
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
}
hashArray[hashVal] = item; // insert item
} // end insert()
hash字符串
二次探测