/* * Code modified from Weiss Textbook: http://users.cis.fiu.edu/~weiss/dsaa_c++/Code * Version author: A. Kalyanaraman * Date: 11/22/2011 * For use in Cpt S 223, School of EECS, WSU */ #include #include "QuadraticProbing.h" using namespace std; /** * Construct the hash table. */ HashTable_qp::HashTable_qp( const string & notFound, int size ) : ITEM_NOT_FOUND( notFound ), array( nextPrime( size ) ) { makeEmpty( ); } /** * Insert item x into the hash table. If the item is * already present, then do nothing. */ void HashTable_qp::insert( const string & x ) { // Insert x as active int currentPos = findPos( x ); if( isActive( currentPos ) ) return; array[ currentPos ] = HashEntry( x, ACTIVE ); // Rehash; see Section 5.5 if( ++currentSize > array.size( ) / 2 ) rehash( ); } /** * Expand the hash table. */ void HashTable_qp::rehash( ) { vector oldArray = array; // Create new double-sized, empty table array.resize( nextPrime( 2 * oldArray.size( ) ) ); for( int j = 0; j < array.size( ); j++ ) array[ j ].info = EMPTY; // Copy table over currentSize = 0; for( int i = 0; i < oldArray.size( ); i++ ) if( oldArray[ i ].info == ACTIVE ) insert( oldArray[ i ].element ); } /** * Method that performs quadratic probing resolution. * Return the position where the search for x terminates. */ int HashTable_qp::findPos( const string & x ) const { /* 1*/ int collisionNum = 0; /* 2*/ int currentPos = hash( x, array.size( ) ); /* 3*/ while( array[ currentPos ].info != EMPTY && array[ currentPos ].element != x ) { /* 4*/ currentPos += 2 * ++collisionNum - 1; // Compute ith probe /* 5*/ if( currentPos >= array.size( ) ) /* 6*/ currentPos -= array.size( ); } /* 7*/ return currentPos; } /** * Remove item x from the hash table. */ void HashTable_qp::remove( const string & x ) { int currentPos = findPos( x ); if( isActive( currentPos ) ) array[ currentPos ].info = DELETED; } /** * Find item x in the hash table. * Return the matching item or ITEM_NOT_FOUND if not found */ const string & HashTable_qp::find( const string & x ) const { int currentPos = findPos( x ); if( isActive( currentPos ) ) return array[ currentPos ].element; else return ITEM_NOT_FOUND; } /** * Make the hash table logically empty. */ void HashTable_qp::makeEmpty( ) { currentSize = 0; for( int i = 0; i < array.size( ); i++ ) array[ i ].info = EMPTY; } /** * Deep copy. */ const HashTable_qp & HashTable_qp:: operator=( const HashTable_qp & rhs ) { if( this != &rhs ) { array = rhs.array; currentSize = rhs.currentSize; } return *this; } /** * Return true if currentPos exists and is active. */ bool HashTable_qp::isActive( int currentPos ) const { return array[ currentPos ].info == ACTIVE; }