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 );
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章