【问题标题】:Need help understanding and adapting this algorithm for hash table需要帮助理解和调整此算法以用于哈希表
【发布时间】:2014-09-06 23:38:12
【问题描述】:

我正在实现一个哈希表作为练习,需要创建一些函数,当负载超过 1.5 时,或者当哈希表中的条目数/桶数超过 1.5 时,该函数将扩大哈希图

我找到了哈希表的另一个实现。但是,不同之处在于我使用的存储桶指向单元格(在运行时动态创建),这些单元格都作为链表相互链接。该实现使用带有预分配结构的哈希表。

所以看起来有点像 [bucket] --> [cell of memory] ​​--> [cell of memory] ​​--> [cell of memory]

这是找到的实现:

static void expandIfNecessary(Hashmap* map) {
// If the load factor exceeds 0.75...
if (map->size > (map->bucketCount * 3 / 4)) {
    // Start off with a 0.33 load factor.
    size_t newBucketCount = map->bucketCount << 1;
    Entry** newBuckets = calloc(newBucketCount, sizeof(Entry*));
    if (newBuckets == NULL) {
        // Abort expansion.
        return;
    }

    // Move over existing entries.
    size_t i;
    for (i = 0; i < map->bucketCount; i++) {
        Entry* entry = map->buckets[i];
        while (entry != NULL) {
            Entry* next = entry->next;
            size_t index = calculateIndex(newBucketCount, entry->hash);
            entry->next = newBuckets[index];
            newBuckets[index] = entry;
            entry = next;
        }
    }

    // Copy over internals.
    free(map->buckets);
    map->buckets = newBuckets;
    map->bucketCount = newBucketCount;
}
}

大部分都适用,除了这部分:

        while (entry != NULL) {
            Entry* next = entry->next;
            size_t index = calculateIndex(newBucketCount, entry->hash);
            entry->next = newBuckets[index];
            newBuckets[index] = entry;
            entry = next;
        }

大概,我想确保链表被分开,以便条目仍然正确连接。我对确切理解这里发生的事情也有点模糊。

我的尝试如下:

         while (entry != NULL) { 
                    // use the pointer of this cell to get to the next cell, store this in a pointer called next
                    // hash the key of the current entry
                    ...

这是我开始不了解实现以及我不确定如何处理我的链接列表的部分。我该如何应用这个?你能解释一下如何适应它吗?

【问题讨论】:

  • 请说明您需要澄清什么?哈希表的概念还是使用现有密钥的当前实现?
  • @YuryLapitsky 我需要知道如何将此实现应用于我的特定数据结构。

标签: c algorithm hashtable


【解决方案1】:

哈希表项在哈希扩大时重新定位到新的桶/箱:

old_index = item->hash % old_bucket_count    
new_index = item->hash % new_bucket_count

出于性能考虑,此实现将每个项目的哈希值存储在 entry-&gt;hash 中。 所做的是取出一个项目,找到它的新索引(桶)并将其放在该桶的链表的前面。

【讨论】:

  • 这是我没有特别理解的:entry->next = newBuckets[index]; newBuckets[index] = entry;
  • 我在顶部的问题中“画出”了一张图表。
  • 你画了一个链表图。
猜你喜欢
  • 2014-09-20
  • 2019-05-01
  • 2011-03-24
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2010-11-04
  • 2014-05-05
  • 2020-01-20
相关资源
最近更新 更多