Consider a hash table T[m] where separate chaining is used such that keys with the same hash value are stored in a heap (dynamically implemented). We assume the existence of a hash h, and that keys in the heap are of type t_Element, and that 2 keys can be compared using comparison operators associated to numbers ($$<, >, ==, ...$$).

  • Write a function that checks if a key belongs to such a hash table.
  • Write a function that calculates the number of distinct elements in a heap.

Difficulty level
Video recording
This exercise is mostly suitable for students
int find_heap_h(Heap h, element e, int start)
{
    if(start >= h->count) return 0;
    if(h->array[start]==e) return 1;
    if(h->array[start]<e) return 0;
    return find_heap_h(h, e, 2*start+1) || find_heap_h(h, e, 2*start+2);
    
}

int find_heap(Heap h, element e)
{
    return find_heap_h(h,e,0);
}

int find(hashtable h, element nb)
{
    return find_heap(h[hash(nb)],nb);
}


int nb_distinct(Heap h)
{
    int i, j;
    int count;
    count =0;
    for(i=0;i<h->count;i++)
    {
        for(j=i+1;j<h->count;j++)
            if(h->array[i]==h->array[j])
                break;
        if(j==h->count)
            count++;
    }
    return count;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Binary tree rotations