DS哈希查找—二次探测再散列

DS哈希查找—二次探测再散列

题目描述

定义哈希函数为H(key) = key%11。输入表长(大于、等于11),输入关键字集合,用二次探测再散列构建哈希表,并查找给定关键字。

输入

测试次数t

每组测试数据格式如下:

哈希表长m、关键字个数n

n个关键字

查找次数k

k个待查关键字

输出

对每组测试数据,输出以下信息:

构造的哈希表信息,数组中没有关键字的位置输出NULL

对k个待查关键字,分别输出:

0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)

样例输入

1

12 10 22 19 21 8 9 30 33

4 41 13

4

22

15

30

41

样例输出

22 9 13 NULL 4 41 NULL 30 19 8 21 33

1 1 1

0 3

1 3 8

1 6 6

Solution:

import java.util.*;
public class Main{
	public static void main(String args[]){
		Scanner scanner = new Scanner(System.in);
		// test times
		int times = scanner.nextInt();
		for (int j = 0; j <times ; j++) {
			int m = scanner.nextInt();// length
			int n = scanner.nextInt();// num
			int[] hash = new int[m];
			for (int i = 0; i <n ; i++) {
				int key = scanner.nextInt();
				int h = key%11;
				// create d
				int t = 1; // di = 1,2,3,..,m-1
				while (hash[h]>0){
					int d;
					if (t%2==1){ // positive
						d = ((t+1)/2)*((t+1)/2);
					}else {
						d = -(t/2)*(t/2);
					}
					h = (key%11+d +m)%m; // Hi = (H(key) + di) MOD m   i=1,2,...,k(k<=m-1)
					t++;
				}
				hash[h] = key;
			}
			for (int i = 0; i < m; i++) {
				if (hash[i] == 0){
					System.out.print("NULL");
				}else {
					System.out.print(hash[i]);
				}
				if (i<m-1){
					System.out.print(" ");
				}
			}
			System.out.println();
			int k = scanner.nextInt(); // the times of search
			for (int i = 0; i <k ; i++) {
				int is_find=0,compare_times=1;
				int key = scanner.nextInt();
				int h = key%11;
				int t = 1;
				while (hash[h]!=key){
					int d;
					if (t%2==1){ // positive
						d = ((t+1)/2)*((t+1)/2);
					}else {
						d = -(t/2)*(t/2);
					}
					if (t>=m || hash[h] ==0){
						is_find =-1;
						break;
					}
					h = (key%11+d +m*t)%m;
					t++;
					compare_times++;
				}
//				compare_times = (h%11 - key%11 +m)%m + 1;
				if (is_find==-1){
					System.out.println(is_find+1+" "+compare_times);
				}else {
					System.out.println(is_find+1+" "+compare_times+" "+(h+1));
				}
			}
		}

	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜饼同学

帮助别人,就是帮助自己,共勉。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值