priority queue with limited space: looking for a good algorithm

后端 未结 8 1670
旧巷少年郎
旧巷少年郎 2020-12-06 02:07

This is not a homework.

I\'m using a small \"priority queue\" (implemented as array at the moment) for storing last N items with smallest value. This is a b

8条回答
  •  囚心锁ツ
    2020-12-06 02:32

    Most priority queues I work are based on linked lists. If you have a pre-determined number of priority levels, you can easily create a priority queue with O(1) insertion by having an array of linked lists--one linked list per priority level. Items of the same priority will of course degenerate into either a FIFO, but that can be considered acceptable.

    Adding and removal then becomes something like (your API may vary) ...

    listItemAdd (&list[priLevel], &item);      /* Add to tail */
    pItem = listItemRemove (&list[priLevel]);  /* Remove from head */
    

    Getting the first item in the queue then becomes a problem of finding the non-empty linked-list with the highest priority. That may be O(N), but there are several tricks you can use to speed it up.

    1. In your priority queue structure, keep a pointer or index or something to the linked list with the current highest priority. This would need to be updated each time an item is added or removed from the priority queue.
    2. Use a bitmap to indicate which linked lists are not empty. Combined with a find most significant bit, or find least significant bit algorithm you can usually test up to 32 lists at once. Again, this would need to be updated on each add / remove.

    Hope this helps.

提交回复
热议问题