【发布时间】:2023-04-02 11:24:01
【问题描述】:
我创建了自己的哈希表实现,其中链表存储在数组的每个条目中(大小为 11)。我正在尝试将哈希表的元素提取到单个数组中,然后对元素数组进行排序。我想过简单地将每个链表提取到结果数组中,然后再对数组进行排序。如下方法所示
//turns the whole hash table into an array
private int[] toArray() {
int sizeOfArray = 0;
for(int i=0; i<11; i++)
{
//calculate the total number of elements in the hashTable
sizeOfArray += hashMap.getList(i).size();
}
int[] result = new int[sizeOfArray];
int indexRes = 0;
//import every entry from the hash table into a single array
for(int i=0; i<11; i++)
{
KeyValuePairLinkedList list = hashMap.getList(i);
//convert the list to an array
int[] listArray = list.toArray();
for(int j=0; j<list.size(); j++)
{
result[indexRes] = listArray[j];
indexRes++;
}
}
return result;
}
但是如果每个链表中的元素已经排序,那么我可以将元素合并到一个数组中,类似于合并排序算法合并两个数组的方式,但是我将合并 11 个数组,而不仅仅是 2 个和我猜这需要很多代码。
另外,假设我只想提取存储在哈希表中的偶数整数,然后在结果数组中对这些整数进行排序。我可以再次使用相同的方法,将整个哈希表提取到一个数组中,然后删除奇数,然后排序。但是必须有更好的方法来做到这一点。
【问题讨论】:
-
每个链表的平均大小是多少?如果它们很小,那么合并它们并没有什么好处。
-
看看这里关于 N 路合并的一些想法:stackoverflow.com/questions/5055909/algorithm-for-n-way-merge
-
如果数组大小为 11,那么列表的平均大小一定非常小。在我看来,这是一个过度优化。运行测试看看你是否需要如此复杂的优化。
标签: java performance linked-list hashtable mergesort