I have a doubly linked list with a sentinel node and I need to sort it using Insertion Sort with O(n^2) complexity. I have written this code but it does not work as it is supposed to.
Any help in general with insertion sort and specifically with a code?
public void insertionSort()
{
int key,i;
int size = getSize();
this.restart();
for(i = 2; i < size; i++)
{
this.next(); // Go to next node
key = this.getVar(); // get the integer a node holds
while(this.hasNext() == 1 && position.prev.var < key && position.var != -1)
{
position.prev.setNext(position.next);
position.next.setPrev(position.prev);
position.setNext(position.prev);
position.setPrev(position.prev.prev);
position.prev.setNext(position);
position.next.setPrev(position);
this.goBack(); // go to the previous node
}
}
}
Size is how many elements my list has. My sentinel has var = -1 so I want to stop when I am at the head that's why I use this.
position.var != -1
and this.hasNext() == 1 is true as long as we are at a position != sentinel node .
In the specific example, I have 35 integers in my list:
5 9 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1
and I want to sort them this way:
9 5 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
UPDATE: The code I use into the insertion sort is the following:
public int getSize()
{
int size = 0;
this.restart();
while(this.hasNext() == 1)
{
size++;
this.next();
}
return size;
}
public void restart()
{
position = header;
previous = Sentinel;
}
public void next()
{
previous = position;
position = position.next;
}
public int getVar()
{
return position.var;
}
public void goBack()
{
position = previous;
previous = previous.prev;
}
public int hasNext()
{
if(position.var != -1)
return 1;
else
return 0;
}
public void setNext(Node next)
{
this.next = next;
}
public void setPrev(Node prev) { this.prev = prev; }
Also, I use a list iterator.
position(or define it), soposition.var != -1is always the same value, indicating it either doesn't sort at all, or never terminates (or maybe something in between).