A refactoring method is required in the work, involving sorting of ultra-long single-chain tables. The original method uses Bubble Sorting (complexity O (N ^ N). The brief code is as follows:
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 }
Test results: it takes about 10 seconds to sort a single-chain table.
Use Insert sort (O (N ^ n-n) to replace the bubble sort reconstruction method. The brief code is as follows:
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 }
It takes about five seconds to sort a single-chain table, which is twice faster than the original one.
It can be seen that the efficiency of insertion sorting for Single-Chain tables is twice faster than that for Bubble sorting. This difference becomes more and more obvious as the length of the chain table increases.
(If you have a better implementation method, please leave a message !)