So I am traversing an BinaryTree and the nodes contain strings as well as if the string appeared more than once while reading the file. I am only looking for the top 10 words that appeared most while reading the file, so essentially I am just comparing an int value.
My problem is I am trying to figure out a way to have an effective way to compare and insert a new node if their count value is greater. So say
I have a tree with…
5
/ \
3 10
/ \
1 15
Say the array size is only size 3. I start at 1, since the array is empty till 5 it will look like after hitting 5…
[1],[3],[5]
When I reach 10 it is greater than everything but I would like to keep it sorted so I need to shift 3 to 1, 5 to 3, and 10 to 5. I want to know if there is a more effective way to do this then to shift after every higher number. It reads a text file with over 10k+ words, so I would like it to be as fast as possible.
If a different data structure would be better for this please let me know. I was thinking a queue or linkedlist but I figured array was less wasted space because it’s only size of 10. I am a student so be gentle too :-x.
One way would be to use a couple of data structures. A suggested way, using a Map and a Min-Heap would be as follows: