Implementing HashTable in Swift?

I am trying to implement a HashTable in Swift. Based on my understanding, hash values ​​are used as the index to be used in the array. The problem is that hash values ​​are very large numbers, for example.

"1" => 4,799,450,059,485,597,623
"2" => 4,799,450,059,485,597,624
"3" => 4,799,450,059,485,597,629

What is the correct way to use these hash values ​​to generate an array index?

class HashTable <K: Hashable, V> {

    private var values : [V?]

    init(size: Int) {
        values = [V?](count: size, repeatedValue: nil)
    }

    func push(key: K, value: V?) {
        values[key.hashValue] = value
    }

    subscript (key: K) -> V? {
        get {
            return values[key.hashValue]
        }
        set {
            push(key, value: newValue)
        }
    }
}
+4
source share
1 answer

I ended up storing LinkedNodes in an array instead of a value.

hashIndex = hashValue % values.count

when searching or deleting, if LinkedList has more than one node, I compare hashValues ​​directly, not hashIndex. (Collision with handle)

Wondering if there is a better solution.

+1
source

Source: https://habr.com/ru/post/1569336/


All Articles