Inserting into Sorted LinkedList Java

前端 未结 7 1320
闹比i
闹比i 2021-01-02 11:59

I have this code below where I am inserting a new integer into a sorted LinkedList of ints but I do not think it is the \"correct\" way of doing things as I know there are s

7条回答
  •  既然无缘
    2021-01-02 12:39

    Linked list isn't the better implementation for a SortedList

    Also, sorting all the list each time you add a new element isn't efficient. The best way is to insert the element directly where it has to be (at his correct position). For this, you can loop all the positions to find where this number belong to, then insert it, or use Collections.binarySearch to let this highly optimised search algorithm do this job for you.

    BinarySearch return the index of the object if the object is found in the list (you can check for duplicates here if needed) or (-(insertion point) - 1) if the object isn't allready in the list (and insertion point is the index where the object need to be placed to maintains order)

提交回复
热议问题