2

I am trying to implement a hash program in go, I did insertion and resolved collisions using linear probing. When I'm trying to retrieve values back, i'm getting different values as I used linear probing to fix collisions.

This is my program : https://play.golang.org/p/7Pmqu6A313

codinggirl
  • 159
  • 1
  • 3
  • 8

1 Answers1

6

The problem in your solution is that you are using "linear probing" for insert operation, but you are not using the same approach for retrieving it.

First of all - I would change your underlining storage to keep whole struct instead of value:

var hasharray [15]Item

Second, I would change the retrieve method to check value of the item with calculated hash index, and after that iterate items one by one to find actual item if there was a collision:

func retrieve(key string) {
    index := hashmethod(key)
    found := false
    for !found {
        item:= hasharray[index];
        if key == item.key {
         found = true;
         fmt.Println(index, item)
        } else if index != size-1 {
            index++
        } else {
            index = 0
        }
    }   
}

See here: https://play.golang.org/p/8JfTpbJcWx

Pavel Morshenyuk
  • 10,891
  • 4
  • 32
  • 38