/**
* 以p为轴对start-end间的节点进行快排(包括start && 不包括end);
* 思路:
* 1.将头节点作为轴节点start,从start.next开始遍历,如果节点小于轴start的值,将该节点插入到轴节点后面;
* 2.将轴节点插入合适位置,即找到最后一个小于轴的节点,将该节点与轴节点值互换,此时就链表分为两部分,小于轴节点和大于轴节点;
* 3.递归的遍历2中两部分节点。
*
* @param p
* @param start
* @param end
*/
private static void quickSortWithLinkedList(Node start, Node end) {
if (start == null || start == end) {
return;
}
Node last = start;
Node cur = start.next;
Node next ;
// 1.默认start作为轴,如果index比start小则移动到start的next
while (cur != null && cur != end) {
next = cur.next;
if (cur.value <= start.value) {
if (start != last) {//为了防止第一个元素小于轴时发生的重复引用
last.next = next;
Node startNext = start.next;
start.next = cur;
cur.next = startNext;
cur = next;
}else{
last = cur;
cur = cur.next;
}
} else {
last = cur;
cur = cur.next;
}
}
// 2.将轴移动到合适的位置,与小于轴的节点的值互换
Node newIndex = start.next;
last = start;
// 找到轴插入的位置last,即找到最后一个小于轴的节点;newIndex != end是为了防止将end加入到计算范围中
while (newIndex != null && newIndex != end && newIndex.value <= start.value) {
last = newIndex;
newIndex = newIndex.next;
}
//
// 将轴与插入位置上节点的值进行交换
int temp = last.value;
last.value = start.value;
start.value = temp;
// 3.进行下一次迭代
quickSortWithLinkedList(start, last);
quickSortWithLinkedList(last.next, end);
}本文出自 “wauoen” 博客,请务必保留此出处http://7183397.blog.51cto.com/7173397/1967055
原文地址:http://7183397.blog.51cto.com/7173397/1967055