Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a HashTable in Swift?

I'm trying to implement a HashTable in Swift. Base on my understanding the hash values are used as the index to be used in the array. The problem is 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's the correct way of using 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)
        }
    }
}
like image 894
aryaxt Avatar asked Dec 29 '14 19:12

aryaxt


1 Answers

I ended up storing LinkedNodes in the array instead of the value.

hashIndex = hashValue % values.count

when searching, or deleting if there are more than one node in the LinkedList, I compare the hashValues directly instead of the hashIndex. (Handle Collision)

Wondering if there is a better solution

like image 164
aryaxt Avatar answered Oct 04 '22 18:10

aryaxt