Code golf: combining multiple sorted lists into a single sorted list

前端 未结 26 2054
余生分开走
余生分开走 2020-12-29 12:42

Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

26条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 13:11

    (all other solutions are O(N) (for the input provided))

    If we let N be the number of elements in the output and k the number of input lists, then you can't do faster than O(N log k) -- suppose that each list was only a single element, and you'd have faster-than-O(N log N) comparison-based sorting.

    Those I've looked at look more like they're O(N*k).

    You can fairly easily get down to O(N log k) time: just put the lists in a heap. This is one of the ways to do I/O-efficient sorting (you can generalize quicksort and heaps/heapsort as well).

    [no code, just commentary]

提交回复
热议问题