6

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)
        }
    }
}
3
  • 2
    A Swift Dictionary is a hash table, so what's the advantage of reimplementing it as an array? (Especially given the fact that Swift doesn't have sparse arrays...) Commented Dec 29, 2014 at 19:22
  • 1
    @matt I know that, The advantage of implementing your own is learning how they work. Doesn't my code create a sparse array? [V?](count: size, repeatedValue: nil) an array of a specific size with default value of nil Commented Dec 29, 2014 at 19:24
  • This article seems to solve this waynewbishop.com/swift/hashtables Commented Dec 29, 2014 at 19:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, You can go through below link this might be helpful : github.com/raywenderlich/swift-algorithm-club/tree/master/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.