1

I have created my own implementation of a hash table in which a linked list is stored in each entry of the array(which has a size of 11). I'm trying to extract elements of the hash table into a single array and then sort the array of elements. I thought about simply extracting each linked list into the resultant array and then sorting the array later. As shown in the method below

//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;
    }

But if the elements in each linked list are already sorted, then I could just merge the elements into a single array, similar to how the merge sort algorithm merges two arrays, however I would be merging 11 arrays rather than just 2 and I'm guessing this would require alot of code.

Also, let's say I wanted to extract just the integers stored in my hashtable which are even, and then sort these integers in the resultant array. I could use the same method again by extracting the whole hash table into one array, and then remove odd integers, then sort. But there must be a better way to do this.

Andrew Brick
  • 246
  • 1
  • 4
  • 18
  • 1
    What's the average size of each linked list? If they're small, then there's not much to gain from merging them. – user253751 Mar 05 '15 at 01:17
  • 2
    Have a look here for some ideas about N-way merge: http://stackoverflow.com/questions/5055909/algorithm-for-n-way-merge – Tim Biegeleisen Mar 05 '15 at 01:18
  • 1
    If array size is 11, then lists average size must be quite low. It seems to me this is an over-optimization. Run tests to see if you need such a complex optimization. – fps Mar 05 '15 at 01:24

1 Answers1

1

one way to do this, if the arrays are already sorted

  • build a min heap of the first element in each array
  • select the minimum, put into the final array + extract next element and insert into the heap

continue doing this until you exhaust all the arrays. each element in the heap would have the value + pointer to what array, and what index it is.

pay attention to the special case in which one of the arrays is exhausted and you no longer need to insert in the heap.

Mircea
  • 9,314
  • 2
  • 25
  • 42