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

480 阅读1分钟

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

\