Java Program For QuickSort On Singly Linked List
QuickSort on Doubly Linked List is discussed here. QuickSort on Singly linked list was given as an exercise. The important things about implementation are, it changes pointers rather swapping data and time complexity is same as the implementation for Doubly Linked List.
In partition(), we consider last element as pivot. We traverse through the current list and if a node has value greater than pivot, we move it after tail. If the node has smaller value, we keep it at its current position.
In QuickSortRecur(), we first call partition() which places pivot at correct position and returns pivot. After pivot is placed at correct position, we find tail node of left side (list before pivot) and recur for left list. Finally, we recur for right list.
Java
public class QuickSortLinkedList
{
static class Node
{
int data;
Node next;
Node( int d)
{
this .data = d;
this .next = null ;
}
}
Node head;
void addNode( int data)
{
if (head == null )
{
head = new Node(data);
return ;
}
Node curr = head;
while (curr.next != null )
curr = curr.next;
Node newNode = new Node(data);
curr.next = newNode;
}
void printList(Node n)
{
while (n != null )
{
System.out.print(n.data);
System.out.print( " " );
n = n.next;
}
}
Node partitionLast(Node start,
Node end)
{
if (start == end ||
start == null ||
end == null )
return start;
Node pivot_prev = start;
Node curr = start;
int pivot = end.data;
while (start != end)
{
if (start.data < pivot)
{
pivot_prev = curr;
int temp = curr.data;
curr.data = start.data;
start.data = temp;
curr = curr.next;
}
start = start.next;
}
int temp = curr.data;
curr.data = pivot;
end.data = temp;
return pivot_prev;
}
void sort(Node start, Node end)
{
if (start == null ||
start == end||
start == end.next )
return ;
Node pivot_prev = partitionLast(start, end);
sort(start, pivot_prev);
if (pivot_prev != null &&
pivot_prev == start)
sort(pivot_prev.next, end);
else if (pivot_prev != null &&
pivot_prev.next != null )
sort(pivot_prev.next.next, end);
}
public static void main(String[] args)
{
QuickSortLinkedList list =
new QuickSortLinkedList();
list.addNode( 30 );
list.addNode( 3 );
list.addNode( 4 );
list.addNode( 20 );
list.addNode( 5 );
Node n = list.head;
while (n.next != null )
n = n.next;
System.out.println(
"Linked List before sorting" );
list.printList(list.head);
list.sort(list.head, n);
System.out.println(
"Linked List after sorting" );
list.printList(list.head);
}
}
|
Output:
Linked List before sorting
30 3 4 20 5
Linked List after sorting
3 4 5 20 30
Please refer complete article on QuickSort on Singly Linked List for more details!
Last Updated :
17 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...