-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashSearch
90 lines (76 loc) · 2.47 KB
/
HashSearch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package Search;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
public class HashSearch {
//初始化哈希表
static int hashLength=7;
static int[] hashTable=new int[hashLength];
static Map<Integer,Integer> hashMap=new HashMap<Integer,Integer>();
//原始数据
static int[] list=new int[] {13, 29, 27, 28, 26, 30, 38};
public static void HashGenerate(Map<Integer,Integer> hashMap,int[] hashTable) {
for(int i=0;i<list.length;i++)
hashMap.put(list[i],i);
}
public static void test1HashMap() {
HashGenerate(hashMap,hashTable);
System.out.println(hashMap.get(29));
}
//哈希表插入
public static void insert(int[] hashTable,int data) {
//哈希函数,除留余数法
int hashAddress=hash(hashTable,data);
//如果不为0,则说明发生冲突
while(hashTable[hashAddress]!=0)
hashAddress=(++hashAddress)%hashTable.length;
//将待插入值存入字典中
hashTable[hashAddress]=data;
}
//哈希表查找
public static int search(int[] hashTable,int data) {
//哈希函数,除留余数法
int hashAddress=hash(hashTable,data);
while(hashTable[hashAddress]!=data) {
//利用开放定址法 解决冲突
hashAddress=(++hashAddress)%hashTable.length;
//查找到开放单元 或者 循环回到原点,表示查找失败
if(hashTable[hashAddress]==0||hashAddress==hash(hashTable,data))
return -1;
}
//查找成功,返回下标
return hashAddress;
}
//构建哈希函数(除留余数法)
public static int hash(int[] hashTable,int data) {
return data%hashTable.length;
}
//展示哈希表
public static String display(int[] hashTable) {
StringBuffer stringBuffer=new StringBuffer();
for(int i:hashTable)
stringBuffer=stringBuffer.append(i+" ");
return String.valueOf(stringBuffer);
}
public static void test2HashKnowledge() {
//创建哈希表
for(int i=0;i<list.length;i++)
insert(hashTable,list[i]);
System.out.println("展示哈希表中的数据:"+display(hashTable));
while(true) {
//哈希查找
System.out.print("请输入要查找的数据:");
int data=new Scanner(System.in).nextInt();
int result=search(hashTable,data);
if(result==-1)
System.out.println("对不起,没有找到!");
else
System.out.println("数据的位置是:"+result);
}
}
public static void main(String[] args) throws IOException{
System.out.println("********哈希查找********");
test1HashMap();
test2HashKnowledge();
}
}