SeparateChainingHashTable

package hash;

import java.util.LinkedList;
import java.util.List;

// SeparateChaining Hash table class
//
// CONSTRUCTION: an approximate initial size or default of 101
//
// ******************PUBLIC OPERATIONS*********************
// void insert( x )       --> Insert x
// void remove( x )       --> Remove x
// boolean contains( x )  --> Return true if x is present
// void makeEmpty( )      --> Remove all items

/**
 * Separate chaining table implementation of hash tables.
 * Note that all "matching" is based on the equals method.
 *
 * @author Mark Allen Weiss
 */
public class SeparateChainingHashTable<AnyType> {
    /**
     * Construct the hash table.
     */
    public SeparateChainingHashTable() {
        this(DEFAULT_TABLE_SIZE);
    }

    /**
     * Construct the hash table.
     *
     * @param size approximate table size.
     */
    public SeparateChainingHashTable(int size) {
        theLists = new LinkedList[nextPrime(size)];
        for (int i = 0; i < theLists.length; i++)
            theLists[i] = new LinkedList<>();
    }

    /**
     * Insert into the hash table. If the item is
     * already present, then do nothing.
     *
     * @param x the item to insert.
     */
    public void insert(AnyType x) {
        List<AnyType> whichList = theLists[myhash(x)];
        if (!whichList.contains(x)) {
            whichList.add(x);

            // Rehash; see Section 5.5
            if (++currentSize > theLists.length)
                rehash();
        }
    }

    /**
     * Remove from the hash table.
     *
     * @param x the item to remove.
     */
    public void remove(AnyType x) {
        List<AnyType> whichList = theLists[myhash(x)];
        if (whichList.contains(x)) {
            whichList.remove(x);
            currentSize--;
        }
    }

    /**
     * Find an item in the hash table.
     *
     * @param x the item to search for.
     * @return true if x isnot found.
     */
    public boolean contains(AnyType x) {
        List<AnyType> whichList = theLists[myhash(x)];
        return whichList.contains(x);
    }

    /**
     * Make the hash table logically empty.
     */
    public void makeEmpty() {
        for (int i = 0; i < theLists.length; i++)
            theLists[i].clear();
        currentSize = 0;
    }

    /**
     * A hash routine for String objects.
     *
     * @param key       the String to hash.
     * @param tableSize the size of the hash table.
     * @return the hash value.
     */
    public static int hash(String key, int tableSize) {
        int hashVal = 0;

        for (int i = 0; i < key.length(); i++)
            hashVal = 37 * hashVal + key.charAt(i);

        hashVal %= tableSize;
        if (hashVal < 0)
            hashVal += tableSize;

        return hashVal;
    }

    private void rehash() {
        List<AnyType>[] oldLists = theLists;

        // Create new double-sized, empty table
        theLists = new List[nextPrime(2 * theLists.length)];
        for (int j = 0; j < theLists.length; j++)
            theLists[j] = new LinkedList<>();

        // Copy table over
        currentSize = 0;
        for (List<AnyType> list : oldLists)
            for (AnyType item : list)
                insert(item);
    }

    private int myhash(AnyType x) {
        int hashVal = x.hashCode();

        hashVal %= theLists.length;
        if (hashVal < 0)
            hashVal += theLists.length;

        return hashVal;
    }

    private static final int DEFAULT_TABLE_SIZE = 101;

    /**
     * The array of Lists.
     */
    private List<AnyType>[] theLists;
    private int currentSize;

    /**
     * Internal method to find a prime number at least as large as n.
     *
     * @param n the starting number (must be positive).
     * @return a prime number larger than or equal to n.
     */
    private static int nextPrime(int n) {
        if (n % 2 == 0)
            n++;

        for (; !isPrime(n); n += 2)
            ;

        return n;
    }

    /**
     * Internal method to test if a number is prime.
     * Not an efficient algorithm.
     *
     * @param n the number to test.
     * @return the result of the test.
     */
    private static boolean isPrime(int n) {
        if (n == 2 || n == 3)
            return true;

        if (n == 1 || n % 2 == 0)
            return false;

        for (int i = 3; i * i <= n; i += 2)
            if (n % i == 0)
                return false;

        return true;
    }


    // Simple main
    public static void main(String[] args) {
        SeparateChainingHashTable<Integer> H = new SeparateChainingHashTable<>();

        long startTime = System.currentTimeMillis();

        final int NUMS = 2000000;
        final int GAP = 37;

        System.out.println("Checking... (no more output means success)");

        for (int i = GAP; i != 0; i = (i + GAP) % NUMS)
            H.insert(i);
        for (int i = 1; i < NUMS; i += 2)
            H.remove(i);

        for (int i = 2; i < NUMS; i += 2)
            if (!H.contains(i))
                System.out.println("Find fails " + i);

        for (int i = 1; i < NUMS; i += 2) {
            if (H.contains(i))
                System.out.println("OOPS!!! " + i);
        }

        long endTime = System.currentTimeMillis();

        System.out.println("Elapsed time: " + (endTime - startTime));
    }

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
print(quadratic_probing_hash_table.get('F')) ``` 5)开散列表:使用链表解决冲突 ```python在SQLite3的Python模块中,可以使用`cursor()`方法在已经连接的数据库上创建一个游标对象,该 class SeparateChainingHashTable: def __init__(self, M): self.M = M self.st = [LinkedList()对象可以用于执行SQL查询和返回结果。 游标是一个指向数据库结果集的指针,可以用于在结果 for i in range(M)] def hash(self, key): return (len(key) * ord(key[0]) + ord(key集中遍历和读取数据。通过游标对象,可以执行`execute()`方法来执行SQL查询,然后使用`[1])) % self.M def put(self, key, value): i = self.hash(key) self.st[i].putfetchone()`、`fetchmany()`或`fetchall()`方法来获取查询结果。另外,游标对象还提供了(key, value) def get(self, key): i = self.hash(key) return self.st[i].get(key) class`execute()`方法的快捷方式,如`executemany()`和`executescript()`。 以下是一个示例代码,演示如何在连接对象上创建游标对象并执行SQL查询: ```python import sqlite3 conn = sqlite3 LinkedList: def __init__(self): self.first = None def put(self, key, value): x = self.connect('example.db') cursor = conn.cursor() # 执行SQL查询 cursor.execute('SELECT * FROM students') # 获取查询结果 result.first while x is not None: if x.key == key: x.value = value return x = = cursor.fetchall() # 输出查询结果 for row in result: print(row) # 关闭游标和连接 cursor.close() x.next self.first = Node(key, value, self.first) def get(self, key): x = self.first conn.close() ``` 在这个例子中,我们创建了一个名为example.db的SQLite数据库,并将其连接到Python while x is not None: if x.key == key: return x.value x = x.next return None中的conn变量。然后,我们使用`cursor()`方法在连接对象上创建了一个游标对象。接下来 class Node: def __init__(self, key, value, next): self.key = key self.value = value ,我们使用游标对象的`execute()`方法来执行了一个SQL查询,查询了students表中的所有数据。然后 self.next = next # 测试代码 separate_chaining_hash_table = SeparateChainingHashTable(30) for key in [',我们使用游标对象的`fetchall()`方法来获取查询结果,并使用一个循环遍历结果并输出。最后,我们关闭了游标和连接对象,释放了资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值