工作中需要重构一个方法,涉及到超长单链表的排序,原先的方法使用冒泡排序实现(复杂度O(n^n)),简要代码如下:
1 public static SingleLink BubbleSort(SingleLink head)
2 {
3 SingleLink minLink = null;
4
5 for (SingleLink currLink1 = head.Next; currLink1 != null; currLink1 = minLink.Next)
6 {
7 if (currLink1.Next == null)
8 {
9 break;
10 }
11
12 minLink = currLink1;
13
14 for (SingleLink currLink2 = currLink1.Next; currLink2 != null; currLink2 = currLink2.Next)
15 {
16 if (currLink2.Data < currLink1.Data)
17 {
18 minLink = currLink2;
19 currLink2 = currLink1;
20 currLink1 = minLink;
21 }
22 }
23 }
24 return head;
25 }
测试结果:单链表完成排序需要大约10秒的时间。
使用插入排序(O(n^n - n))代替冒泡排序重构方法,简要代码如下:
1 public static SingleLink InsertSort(SingleLink head)
2 {
3 SingleLink preLink = head;
4 SingleLink preNext = head.Next;
5 SingleLink minLink = null;
6
7 for (SingleLink currLink1 = head.Next; currLink1 != null; currLink1 = minLink.Next)
8 {
9 if (currLink1.Next == null)
10 {
11 break;
12 }
13
14 minLink = currLink1;
15
16 for (SingleLink currLink2 = currLink1.Next; currLink2 != null; currLink2 = currLink2.Next)
17 {
18 if (currLink2.Data < currLink1.Data)
19 {
20 minLink = currLink2;
21 currLink2 = currLink1;
22 currLink1 = minLink;
23 preLink.Next = currLink1;
24 currLink2.Next = currLink1.Next;
25 currLink1.Next = preNext;
26
27 if (preNext != currLink2)
28 {
29 preNext.Next = currLink2;
30 }
31 }
32 preNext = currLink2;
33 }
34 preLink = minLink;
35 preNext = minLink.Next;
36 }
37 return head;
38 }
单链表完成排序需要大约5秒,比原先的快了一倍。
由此可见,对于单链表的排序,插入排序的效率比冒泡排序要快一倍,这种差异随着链表长度的增加而越发明显。
(如果大家有更好的实现方法可以给我留言!)