Inserting into Sorted LinkedList Java

前端 未结 7 1287
闹比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:42

    You can do it in log (N) time Complexity simply. No need to iterate through all the values. you can use binary search to add value to sorted linked list.just add the value at the position of upper bound of that function. Check code... you may understand better.

        public static int ubound(LinkedList<Integer> ln, int x) {
            int l = 0;
            int h = ln.size();
            while (l < h) {
                int mid = (l + h) / 2;
                if (ln.get(mid) <= x) l = mid + 1;
                else h = mid;
            }
            return l;
        }
    
        public void solve() 
        {
            LinkedList<Integer> ln = new LinkedList<>();
            ln.add(4);
            ln.add(6);
            ln.add(ubound(ln, 5), 5);
            out.println(ln);
    
        }
    

    Output : [4, 5, 6]

    you can learn about binary search more at : https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/

    0 讨论(0)
提交回复
热议问题