문제

This is my implementation of insertion sort in java for doubly linked list. I have checked for many values and it gives me correct output. My question is:

  1. I don't know how to calculate the algorithm time for this I mean O(n)
  2. Can this be optimized? Can anyone point to code which is more optimized?

Note : Code uses sentinel node to that points to start of linked list i.e sentinel node.next points to starting node of linked list and sentinel node.PREV point to last node of linked list and head points to sentinel node.

public void sortInsertionAsce(){
            DListNode marker,aheadOfCurrent;;
            DListNode current = head.getNext();
            aheadOfCurrent = current.getNext();
            marker=current;
            while(aheadOfCurrent.getNext()!=current){
            if(marker.getItem()>aheadOfCurrent.getItem()){
                swap(aheadOfCurrent,marker);
                marker=aheadOfCurrent;
                    while(aheadOfCurrent.getPrev()!=current){
                        aheadOfCurrent=aheadOfCurrent.getPrev();
                        if(aheadOfCurrent.getPrev().getItem()>aheadOfCurrent.getItem()){
                            swap(aheadOfCurrent.getPrev(),aheadOfCurrent);
                        }
                    }
                    aheadOfCurrent=marker;
                }
                    marker=aheadOfCurrent;
                    aheadOfCurrent=aheadOfCurrent.getNext();
            }
         } 
도움이 되었습니까?

해결책

it's O(N^2), beacause 1 nested loop. and all 2 loops iterate over all list

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top