法 | 时间复杂度(平均) | 时间复杂度(最坏) | 时间复杂度(最好) | 空间复杂度 | 稳定性 | 复杂性 |
直接插入排序 | O(n2)O(n2) | O(n2)O(n2) | O(n)O(n) | O(1)O(1) | 稳定 | 简单 |
希尔排序 | O(nlog2n)O(nlog2n) | O(n2)O(n2) | O(n)O(n) | O(1)O(1) | 不稳定 | 较复杂 |
直接选择排序 | O(n2)O(n2) | O(n2)O(n2) | O(n2)O(n2) | O(1)O(1) | 不稳定 | 简单 |
堆排序 | O(nlog2n)O(nlog2n) | O(nlog2n)O(nlog2n) | O(nlog2n)O(nlog2n) | O(1)O(1) | 不稳定 | 较复杂 |
冒泡排序 | O(n2)O(n2) | O(n2)O(n2) | O(n)O(n) | O(1)O(1) | 稳定 | 简单 |
快速排序 | O(nlog2n)O(nlog2n) | O(n2)O(n2) | O(nlog2n)O(nlog2n) | O(nlog2n)O(nlog2n) | 不稳定 | 较复杂 |
归并排序 | O(nlog2n)O(nlog2n) | O(nlog2n)O(nlog2n) | O(nlog2n)O(nlog2n) | O(n)O(n) | 稳定 | 较复杂 |
基数排序 | O(d(n+r))O(d(n+r)) | O(d(n+r))O(d(n+r)) | O(d(n+r))O(d(n+r)) | O(n+r)O(n+r) | 稳定 | 较复杂 |
/**
* 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) {
if (head == null || head.next == null) {
return head;
}
ListNode mid = getmid(head);//取中点,前半段
ListNode midnext = mid.next;//后半段
mid.next = null;
return merge(sortList(head), sortList(midnext));//递归前半段,后半段
}
//取中点
public ListNode getmid(ListNode head) {
if (head == null || head.next == null) {
return head;
}
//快慢指针
ListNode slow = head;
ListNode quick = head;
//快指针结束,慢指针到达中点
while (quick.next != null && quick.next.next!= null) {
slow = slow.next;
quick = quick.next.next;
}
return slow;
}
//nlogn归并排序
public ListNode merge(ListNode a, ListNode b) {
//建立一个新的链表l
ListNode l = new ListNode(0);
//aa,bb,ll为工作指针
ListNode aa = a;
ListNode bb = b;
ListNode ll = l;
while (aa != null && bb != null) {
if (aa.val < bb.val) {
ll.next = aa;
aa = aa.next;
} else {
ll.next = bb;
bb = bb.next;
}
ll = ll.next;//提到外面
}
//其中任意一条走完,直接将剩余的加在后面即可,aa,bb不需要移动
if (aa != null) {
ll.next = aa;
}
if (bb != null) {
ll.next = bb;
}
return l.next;//返回l.next
}
}