What's faster: inserting into a priority queue, or sorting retrospectively?

前端 未结 10 1460
闹比i
闹比i 2020-12-12 16:58

What\'s faster: inserting into a priority queue, or sorting retrospectively?

I am generating some items that I need to be sorted at the end. I was wondering, what is

10条回答
  •  Happy的楠姐
    2020-12-12 17:22

    There are a lot of great answers to this question. A reasonable "rule of thumb" is

    • If you have all your elements "up front" then choose sorting.
    • If you will be adding elements / removing minimal elements "on the fly" then use a priority queue (e.g., heap).

    For the first case, the best "worst-case" sort is heap sort anyway and you'll often get better cache performance by just focusing on sorting (i.e. instead of interleaving with other operations).

提交回复
热议问题