📅  最后修改于: 2023-12-03 15:37:05.382000             🧑  作者: Mango
本程序使用双向链表实现快速排序算法。快速排序是一种常见的排序算法,其时间复杂度为O(nlogn)。本程序使用轴点元素选取的方法,将链表分割成左右两个子链表进行递归排序。
程序的实现主要包括以下几个步骤:
public class DoubleListNode {
int val;
DoubleListNode prev, next;
public DoubleListNode(int val) {
this.val = val;
}
}
public static void quicksort(DoubleListNode head, DoubleListNode tail) {
if (head == null || tail == null || head == tail) return;
DoubleListNode pivot = partition(head, tail);
quicksort(head, pivot.prev);
quicksort(pivot.next, tail);
}
private static DoubleListNode partition(DoubleListNode head, DoubleListNode tail) {
int pivot = tail.val;
DoubleListNode p = head;
for (DoubleListNode q = head; q != tail; q = q.next) {
if (q.val < pivot) {
int tmp = p.val;
p.val = q.val;
q.val = tmp;
p = p.next;
}
}
int tmp = p.val;
p.val = tail.val;
tail.val = tmp;
return p;
}
DoubleListNode head = new DoubleListNode(3);
head.next = new DoubleListNode(2);
head.next.prev = head;
head.next.next = new DoubleListNode(1);
head.next.next.prev = head.next;
head.next.next.next = new DoubleListNode(4);
head.next.next.next.prev = head.next.next;
quicksort(head, head.next.next.next);
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
运行上述程序,输出结果为:
1 2 3 4
可知程序能正确地对双向链表进行快速排序。
本程序展示了使用双向链表实现快速排序算法的过程,同时也展示了如何使用Java语言实现双向链表的节点类和对链表进行操作的方法。