I am optimizing an implementation of a sorted LinkedList.
To insert an element I traverse the list and compare each element until I have the correct index, and then break loop and insert.
I would like to know if there is any other way that I can insert the element at the same time as traversing the list to reduce the insert from O(n + (n capped at size()/2)) to O(n).
A ListIterator is almost what Im after because of its add() method, but unfortunately in the case where there are elements in the list equal to the insert, the insert has to be placed after them in the list. To implement this ListIterator needs a peek() which it doesnt have.
edit: I have my answer, but will add this anyway since a lot of people havent understood correctly:
I am searching for an insertion point AND inserting, which combined is higher than O(n)
I’d favor Péter Török suggestion, but I’d still like to add something for the iterator approach:
Note that
ListIteratorprovides aprevious()method to iterate through the list backwards. Thus first iterate until you find the first element that is greater and then go to the previous element and calladd(...). If you hit the end, i.e. all elements are smaller, then just calladd(...)without going back.