/* 哈希结点 */
class TheNode {
int key; // 链表中的键
TheNode next; // 下一个节点
//
public String toString() {
return "TheNode [key=" + key + "]";
}
}
/* 在哈希表中查找关键字 */
public class HashTableSearch {
public static int hashSearch( int[] data, int key ) {
int index = -1;
int prime = 0;
// 寻找小于等于最接近链表长度的质数
/* for ( int i = data.length; i > 1; i-- ) {
if ( isPrimes( i ) ) {
prime = i;
break;
}
}*/
Map mapDataIndex = new HashMap<>();
// 寻找小于或等于最接近链表长度的质数,并遍历所有元素保存索引到 mapDataIndex
for ( int i = data.length; i > 0; i-- ) {
if ( isPrimes( i ) ) {
if ( prime == 0 ) {
prime = i;
}
}
mapDataIndex.put( data[ i - 1 ], i - 1 );
//System.out.println( data[ i ] + " " + i );
}
System.out.println( mapDataIndex );
// 创建哈希表
TheNode[] hashTable = createHashTable( data, prime );
// 查找哈希表中是否包含这个值
int tableKey = key % prime;
TheNode cur = hashTable[ tableKey ];
while ( cur != null && cur.key != key ) {
cur = cur.next;
}
//boolean flag = false;
if ( cur == null ) {
//flag = false; // 没找到
return -1;
} else {
//flag = true; // 找到了
return ( int ) mapDataIndex.get( key );
}
}
/* 用求余、链表法构建哈希表 */
public static TheNode[] createHashTable( int[] data, int prime ) {
System.out.println( prime );
TheNode[] hashtable = new TheNode[ prime ];
int key; // 哈希函数计算的单元地址
for ( int i = 0; i < data.length; i++ ) {
TheNode node = new TheNode();
node.key = data[ i ];
key = data[ i ] % prime;
System.out.println( key + " " + node.key );
if ( hashtable[ key ] == null ) {
hashtable[ key ] = node;
} else {
TheNode current = hashtable[ key ];
while ( current.next != null ) {
current = current.next;
}
current.next = node;
}
}
return hashtable;
}
// 判断是否是质数
public static boolean isPrimes( int n ) {
for ( int i = 2; i <= Math.sqrt( n ); i++ ) {
if ( n % i == 0 ) {
return false;
}
}
return true;
}
// 查找到就返回元素的索引索引
public static void main( String[] arr ) {
//
int search = 19;
// 数组不需要排序
int[] arr = { 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
int index = hashSearch( arr, search );
System.out.println( "是否查找到了这个值:" + search + ",它的索引是:" + index );
}
}