Question

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();
            }
         } 
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top