Search code examples
c++vectorhashmaphashtablehash-collision

Hash Tables: why doesn't this code resolve collisions?


This insert function doesn't seem to insert correctly and overwrites previous entries. Also the duplicate check doesn't work as intended and only works half the time.

HT::HT(const unsigned& tblSize) {

  //Hash table size equal to size passed or default size TBL_SIZE
  hsize = tblSize;
  //Pointer table defualt 0
  psize = 0;

  //reisze tables
  hTable.resize(hsize);
  pTable.resize(hsize);

  //set unused values to empty($$$)
  for(unsigned i = 0; i < hsize; i++)
    hTable[i].key = FREE;
}


//implementation of insert function
void HT::insert(const Entry& record) {

  //assign integer value to index via hash function
  int index = (hash(record.key) % 31);

  //logic to insert into hash table
  for(unsigned i = 0; i < hsize; i++) {
    //inserting into table with linear probing collision resolution

    //inserting into hash table with linear probing as collision resolution
    if (hTable[(index+i)%hsize].key == FREE) {

      hTable[index] = record;
      pTable[psize] = &hTable[(index+i)%hsize];
      psize++;
      cout << " Entry = " << ((index+i)%hsize) << endl;

      return;
    }

    //Duplicate key check
    else if (hTable[(index+i)%hsize].key == record.key) {
      cout << " Entry = Not Inserted - Duplicate key!! " << endl; return;
    }

    //Capacity of table check
    else if (i == hsize - 1) {
      cout << " Not Inserted -  Table full!! " << endl; return;
    }

  } //end for loop
}

It seems to insert fine and the duplicate key check works on one data set but not the other with more data values that fill the table to TBL_SIZE = 31. Also the FREE constant sets all vector values to $$$ to designate a free spot.


Solution

  • //inserting into hash table with linear probing as collision resolution
    if (hTable[(index+i)%hsize].key == FREE) {
    
      hTable[index] = record;
    

    You don't want to insert into [index] when [(index + i)%hsize] is the free location.