java 实现哈希查找的例子

/* 哈希结点 */
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 );
	}

}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值