I know that you are looking for a specialized data structure, but what about using a simple data structure, but sorting it is lazy? You can add new lines to a dynamic array and then sort the array (using qsort ) when you need to print them.
I think this would be better because printing all the lines is probably much less common than adding / inserting the lines. Therefore, you should make adding lines cheaper (in this case, O (1) is amortized), and printing can be more expensive (in this case, O (n log n)). It also simplifies your data structures and allows the C standard library to handle complex parts.
You can do this a little better by keeping a flag that keeps track of whether all data is already known for sorting; this method prints multiple times (or, suppose you try to write a BASIC interpreter many times) will also be cheap. This flag can also be useful if you expect strings to be usually entered in order; then as you add each line:
alreadySorted = alreadySorted && (new_line_number > last_line_number)
I note that you did not indicate what would happen if a line was added that reuses the existing line number. If you want to replace the old line, you can customize this approach using a stable view and then iterating along the lines to delete lines with duplicate numbers, keeping only the last.
(If you want to make qsort stable for this case, instead of saving only a row for each row, you can save some additional metadata with it (any monotonously increasing counter will do, for example, the current time or just the total number of rows when adding a row). Then, for the comparison function you give qsort , you just need to use this extra data to resolve the links from duplicate line numbers.)
One of the drawbacks of this approach is that deleting rows will not be quick or will not immediately restore memory. However, you did not indicate whether deleting the line is a requirement; even if it is, it is likely to be a rare operation (so being a little more time inefficient or a little more spatially inefficient may be acceptable).
jamesdlin
source share