1

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.

inityk
  • 317
  • 1
  • 7
  • 17
  • "I'm not able to generate expected output" what is your input, what is your expected output, what is your actual output? – Andy Turner Nov 25 '15 at 14:48
  • @AndyTurner Input :[20,10,30,5] Expected Output is in sorted sequence:[5,10,20,30] However I'm getting exactly what I insert – inityk Nov 25 '15 at 14:53

1 Answers1

3

You can't swap values like this:

public void swap(int a , int b)
{
    int t;

    t = a;
    a = b;
    b = t;
}

Java is pass-by-value, so a and b are local variables to swap; any changes you make to the values are lost when swap returns.

However, you could write:

public void swap(Node a , Node b)
{
    int t;

    t = a.data;
    a.data = b.data;
    b.data = t;
}

because this is updating fields on the two node instances, which are still passed by value, but the value is the reference to the instances.

Community
  • 1
  • 1
Andy Turner
  • 122,430
  • 10
  • 138
  • 216