分析:
因为单链表只能单向前进,所以不能采用常见的快排模式。
我们只需要两个指针p和q,初始分别为head和head.next,这两个指针均往next方向移动,移动的过程中保持p之前的key都小于选定的key,p和q之间的key都大于选定的key,那么当q走到末尾的时候便完成了一次支点的寻找。后面每个部分继续递归实现。
代码:
/**
* Created by wqh on 2017/8/18.
*/
public class NodeQuickSort {
public Node head;
public Node cur;
NodeQuickSort(Node head){
this.head = head;
this.cur = head;
}
public void insert(int value){
Node temp = new Node(value);
cur.next = temp;
cur = temp;
}
public Node partition(Node start, Node end){
Node p = start;
Node q = start.next;
while (q != end){
if(q.value < start.value){
p = p.next;
swap(p, q);
}
q = q.next;
}
swap(start, p);
return p;
}
public void quickSort(Node start, Node end){
if(start != end){
Node partion = partition(start, end);
quickSort(start, partion);
quickSort(partion.next, end);
}
}
public static void swap(Node n1, Node n2){
int temp = n1.value;
n1.value = n2.value;
n2.value = temp;
}
public static void main(String[] args) {
Node head = new Node(4);
NodeQuickSort test = new NodeQuickSort(head);
test.insert(5);
test.insert(3);
test.insert(8);
test.insert(6);
test.insert(2);
test.insert(7);
test.quickSort(head, null);
Node cur = head;
while (cur != null){
System.out.print(cur.value + " ");
cur = cur.next;
}
}
}
class Node{
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}