我创建了自己的哈希表实现,其中链表存储在数组的每个条目中(大小为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个我猜这需要很多代码。
另外,假设我只想提取存储在哈希表中的整数,这些整数是偶数,然后在结果数组中对这些整数进行排序。我可以通过将整个哈希表提取到一个数组中再次使用相同的方法,然后删除奇数整数,然后排序。但必须有更好的方法来做到这一点。
答案 0 :(得分:1)
一种方法,如果数组已经排序
继续执行此操作,直到耗尽所有数组。 堆中的每个元素都有值+指向什么数组的指针,以及它是什么索引。
注意其中一个数组已耗尽并且您不再需要在堆中插入的特殊情况。