By 'list' i mean the English word, not necessary linked list. You can use any data structure. However, PHP has inbuilt support for some data structures: https://www.php.net/manual/en/spl.datastructures.php from which min heap is seeming suitable to me for my problem. Though i don't know how to use the PHP's min heap facility.
Say a loop is reading from database and outputting some user ids and with each user id a score of how similar the user's name is compared to an inputted word. After end of the loop, i want to view top 10 users in decreasing order of the score. The score calculation is done inside the loop.
Easiest way for me to do this is: While calculating the scores (inside the loop), store all user ids with their scores in an array. After all scores are stored, sort the array using PHP's inbuilt sort facility. Display the top 10 elements from the array.
But why bother (the system) in storing and sorting all the scores when i want just 10 top users. So, any good method?
Another possible solution i'm imagining is like, feel free to ignore:
Maintaining a linked list of scores in decreasing order. After it reaches length 10, then when receive a new score, check whether it's smaller than the score in right-most node (the 10th node), if it's then discard it, if not then discard the right-most node and insert the new score at its proper place by checking whether it's smaller than 5th (middle) element of the linked list, if it's then compare the same with 7th (middle of 5th and 9th) and so on.
PS: I've no problem with top k elements being sorted after they all have been selected.
Outputting the above created min heap:
Check whether
$topMatches
isEmpty()
or alternatively itscount()
is 0. If it's thenreturn;
. Next: