用链表来排序,速度会不会更快?为什么大家不用链表来排序?
思路是遍历所有数字,一个个插入双向链表,设置一个标记来标记中间节点,然后数字双向走,比中间节点小的往前,比中间节点大的往后,设置一个标记flag=0,往前-1,往后+1,当flag=2时中间节点往后走一个,-2时往前走一个,最后遍历整个链表就可以了。
1 public class LinkObj<T> where T: IComparable 2 { 3 public LinkObj<T> next; 4 public LinkObj<T> prev; 5 public T target; 6 7 public LinkObj(T t) 8 : this(t, null, null) { } 9 10 public LinkObj(T t, LinkObj<T> n, LinkObj<T> p) 11 { 12 this.target = t; 13 this.next = n; 14 this.prev = p; 15 } 16 } 17 18 public class LinkSort 19 { 20 public static List<T> ASC<T>(List<T> list) where T : IComparable 21 { 22 if (list == null || list.Count == 0) 23 return list; 24 25 LinkObj<T> head, mid, tail; 26 head = mid = tail = null; 27 int midFlag = 0; 28 foreach (var item in list) 29 { 30 if (head == null) 31 head = mid = tail = new LinkObj<T>(item); 32 else 33 { 34 var l = new LinkObj<T>(item); 35 var t = mid; 36 if (item.CompareTo(t.target) > 0) 37 { 38 while (item.CompareTo(t.target) > 0) 39 { 40 if (t.next != null) 41 t = t.next; 42 else 43 { 44 t.next = l; 45 l.prev = t; 46 tail = l; 47 t = null; 48 break; 49 } 50 } 51 if (t != null) 52 { 53 l.next = t; 54 l.prev = t.prev; 55 t.prev = l; 56 l.prev.next = l; 57 } 58 midFlag++; 59 } 60 else 61 { 62 while (item.CompareTo(t.target) < 0) 63 { 64 if (t.prev != null) 65 t = t.prev; 66 else 67 { 68 t.prev = l; 69 l.next = t; 70 head = l; 71 t = null; 72 break; 73 } 74 } 75 if (t != null) 76 { 77 l.prev = t; 78 l.next = t.next; 79 t.next = l; 80 l.next.prev = l; 81 } 82 midFlag--; 83 } 84 } 85 86 if (midFlag == 2) 87 mid = mid.next; 88 else if (midFlag == -2) 89 mid = mid.prev; 90 } 91 92 var result = new List<T>(); 93 var t2 = head; 94 while (t2 != null) 95 { 96 result.Add(t2.target); 97 t2 = t2.next; 98 } 99 return result; 100 } 101 }