单链表的快排实现

分析:
因为单链表只能单向前进,所以不能采用常见的快排模式。

我们只需要两个指针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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值