java数据结构和算法------哈希查找

 1 package iYou.neugle.search;
 2 
 3 public class Hash_search {
 4     private static int m = 13;
 5     private static int[] hash = new int[m];
 6     private static int[] array = new int[] { 13, 25, 2, 60, 39, 52 };
 7 
 8     public static void main(String[] args) {
 9         InsertHash();
10         System.out.println("哈希表建立如下:");
11         System.out.print("[");
12         for (int i = 0; i < hash.length; i++) {
13             System.out.print(hash[i]);
14             if (i != hash.length - 1) {
15                 System.out.print(",");
16             }
17         }
18         System.out.println("]");
19         System.out.println("39在哈希表中的位置为:" + SearchHash(39));
20     }
21 
22     public static void InsertHash() {
23         // 除法取余法
24         for (int i = 0; i < array.length; i++) {
25             int value = array[i];
26             int address = value % m;
27             while (hash[address] != 0) {
28                 address = (++address) % m;
29             }
30             hash[address] = value;
31         }
32     }
33 
34     public static int SearchHash(int key) {
35         // 开放地址法
36         int address = key % m;
37         while (hash[address] != 0 && hash[address] != key) {
38             address = (++address) % m;
39         }
40 
41         if (hash[address] == 0) {
42             return -1;
43         }
44         return address;
45     }
46 }
原文地址:https://www.cnblogs.com/niuxiaoha/p/4626096.html