Inserting into Sorted LinkedList Java

前端 未结 7 1344
闹比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条回答
  •  猫巷女王i
    2021-01-02 12:25

    You have to find where to insert the data by knowing the order criteria.

    The simple method is to brute force search the insert position (go through the list, binary search...).

    Another method, if you know the nature of your data, is to estimate an insertion position to cut down the number of checks. For example if you insert 'Zorro' and the list is alphabetically ordered you should start from the back of the list... or estimate where your letter may be (probably towards the end). This can also work for numbers if you know where they come from and how they are distributed. This is called interpolation search: http://en.wikipedia.org/wiki/Interpolation_search

    Also think about batch insert: If you insert a lot of data quickly you may consider doing many insertions in one go and only sort once afterwards.

提交回复
热议问题