单链表的快速排序

来源:互联网 发布:标准数据公司 编辑:程序博客网 时间:2024/06/06 08:42

单链表实现的快速排序如下图所示:

既然两个指针都是从前往后遍历,那么链表值进行交换就简单了。找到支点后,支点左边和支点右边进行子问题递归,就回到快排原来的思路上去了。

代码实现

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {   public  ListNode sortList(ListNode head) {  return sort(head,null);    }            public  ListNode sort(ListNode head,ListNode end){        if(head!=end){         ListNode a=GetPartion(head,end);            sort(head, a);            sort(a.next,end);        }return head;    }        public  ListNode GetPartion(ListNode head,ListNode end){    int key=head.val;    ListNode p=head;    ListNode q=head.next;        while(q!=end){    if(q.val<key){   //把所有小于比较值放在比较值的前面    p=p.next;      swap(p,q);    }    q=q.next;        }    swap(head,p);  //交换比较值与p的位置return p;            }private  void swap(ListNode p,ListNode q) {Integer aa=p.val;p.val=q.val;q.val=aa;}}


原创粉丝点击