Maybe I have done too much SQL, but for me it is trivial and easier to do than in most other languages. PostgreSQL will execute the query below in O(n) if there is no index and O(1) if there is an index on num.
Does any other language implement this in a better way? While also still giving a O(n) time complexity and O(1) space? I may have to implement my own top-n heapsort then, or my own top-n insertion sort.
SELECT * FROM (
SELECT
row_number() AS n, num
FROM t
ORDER BY num DESC
LIMIT 5
) top5 WHERE n IN (1, 3, 5);
This is assuming we do not care about ties. If we care about ties it gets a bit messier but not that bad.
In other languages, this task does not require a sort. It's just a for loop. The fact that you need a nested table and a sort illustrates my point about SQL making some easy problems hard (maybe harder is more accurate).
Does any other language implement this in a better way? While also still giving a O(n) time complexity and O(1) space? I may have to implement my own top-n heapsort then, or my own top-n insertion sort.
This is assuming we do not care about ties. If we care about ties it gets a bit messier but not that bad.