I've been doing this problem for a while now. I created one file named quickSort.java - chose the last element of a list as a pivot element. and tried to sort the numbers but somehow I'm not able to generate expected output. I tried so many probable options but I'm stuck! Please help to get the correct solution.
Here's my code of the file: quickSort.java
public void quickFun(Node node)
{
Node new_node = node;
/* To find the last element as pivot*/
while(new_node.next!=null)
{
new_node = new_node.next;
}
Node head = node;
Node tail = new_node;
quickSort(head, tail);
}
public void quickSort(Node head, Node tail)
{
Node q = partition(head,tail);
if(head!=q && head!=q.prev)
{
quickSort(head, q.prev);
}
if(tail!=q && tail!=q.next)
{
quickSort(q.next, tail);
}
}
public Node partition(Node low, Node high){
int p = high.data;
Node i = low.prev;
for(Node j = low; j!=high; j=j.next)
{
if(j.data <= p)
{
if(i==null)
{
i = low;
}
else
{
i = i.next;
}
swap(i.data, j.data);
}
}
if(i==null)
{
i = low;
}
else
{
i = i.next;
}
swap(i.data, high.data);
return i;
}
public void swap(int a , int b)
{
int t;
t = a;
a = b;
b = t;
}
Here quickFun receives head of the inserted LinkedList as an argument. I'm basically stuck at quickSort(Node, Node) condition.
Please help me here to solve this problem.