說到排序,大家第一反應基本上是內排序,是的,演演算法嘛,玩的就是記憶體,然而記憶體是有限制的,總有裝不下的那一天,此時就可以來玩玩
外排序,當然在我看來,外排序考驗的是一個程式設計師的架構能力,而不僅僅侷限於排序這個層次。
 
一:N 路歸併排序
1. 概序
我們知道演演算法中有一種叫做分治思想,一個大問題我們可以採取分而治之,各個突破,當子問題解決了,大問題也就 KO 了,還有一點我們知道
內排序的歸併排序是採用二路歸併的,因為分治後有 LogN 層,每層兩路歸併需要 N 的時候,最後複雜度為 NlogN,那麼外排序我們可以將這個 “二”
擴大到 M,也就是將一個大檔案分成 M 個小檔案,每個小檔案是有序的,然後對應在記憶體中我們開 M 個優先佇列,每個佇列從對應編號的檔案中讀取
TopN 條記錄,然後我們從 M 路佇列中各取一個數字進入中轉站佇列,並將該數字打上佇列編號標記,當從中轉站出來的最小數字就是我們最後要排
序的數字之一,因為該數字打上了佇列編號,所以方便我們通知對應的編號佇列繼續出數字進入中轉站佇列,可以看出中轉站一直儲存了 M 個記錄,
當中轉站中的所有數字都出隊完畢,則外排序結束。如果大家有點蒙的話,我再配合一張圖,相信大家就會一目瞭然,這考驗的是我們的架構能力。

圖中這裡有個 Batch 容器,這個容器我是基於效能考慮的,當 batch=n 時,我們定時重新整理到檔案中,保證記憶體有足夠的空間。
 
2. 構建
<1> 生成資料
這個基本沒什麼好說的,採用隨機數生成 n 條記錄。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#region 隨機生成資料
///

/// 隨機生成資料
///執行生成的資料上線 ///

public static void CreateData(int max)
{
    var sw = new StreamWriter(Environment.CurrentDirectory + “//demo.txt”);

    for (int i = 0; i < max; i++)     {         Thread.Sleep(2);         var rand = new Random((int)DateTime.Now.Ticks).Next(0, int.MaxValue >> 3);

        sw.WriteLine(rand);
    }
    sw.Close();
}
#endregion

 
<2> 切分資料
根據實際情況我們來決定到底要分成多少個小檔案,並且小檔案的資料必須是有序的,小檔案的個數也對應這記憶體中有多少個優先佇列。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

#region 將資料進行分份
///

/// 將資料進行分份
/// 每頁要顯示的條數 ///

public static int Split(int size)
{
    //檔案總記錄數
    int totalCount = 0;

    //每一份檔案存放 size 條 記錄
    List small = new List();

    var sr = new StreamReader((Environment.CurrentDirectory + “//demo.txt”));

    var pageSize = size;

    int pageCount = 0;

    int pageIndex = 0;

    while (true)
    {
        var line = sr.ReadLine();

        if (!string.IsNullOrEmpty(line))
        {
            totalCount++;

            //加入小集合中
            small.Add(Convert.ToInt32(line));

            //說明已經到達指定的 size 條數了
            if (totalCount % pageSize == 0)
            {
                pageIndex = totalCount / pageSize;

                small = small.OrderBy(i => i).Select(i => i).ToList();

                File.WriteAllLines(Environment.CurrentDirectory + “//” + pageIndex + “.txt”, small.Select(i => i.ToString()));

                small.Clear();
            }
        }
        else
        {
            //說明已經讀完了,將剩餘的 small 記錄寫入到檔案中
            pageCount = (int)Math.Ceiling((double)totalCount / pageSize);

            small = small.OrderBy(i => i).Select(i => i).ToList();

            File.WriteAllLines(Environment.CurrentDirectory + “//” + pageCount + “.txt”, small.Select(i => i.ToString()));

            break;
        }
    }

    return pageCount;
}
#endregion

 
<3> 加入佇列
我們知道記憶體佇列存放的只是小檔案的 topN 條記錄,當記憶體佇列為空時,我們需要再次從小檔案中讀取下一批的 TopN 條資料,然後放入中轉站
繼續進行比較。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#region 將資料加入指定編號佇列
        ///

        /// 將資料加入指定編號佇列
        ///

        /// 佇列編號         /// 檔案中跳過的條數         ///         /// 需要每次讀取的條數         public static void AddQueue(int i, List> list, ref int[] skip, int top = 100)
        {
            var result = File.ReadAllLines((Environment.CurrentDirectory + “//” + (i + 1) + “.txt”))
                             .Skip(skip[i]).Take(top).Select(j => Convert.ToInt32(j));

            //加入到集合中
            foreach (var item in result)
                list[i].Eequeue(null, item);

            //將個數累計到 skip 中,表示下次要跳過的記錄數
            skip[i] += result.Count();
        }
        #endregion

 
<4> 測試
最後我們來測試一下:
資料量:short.MaxValue 。
記憶體存放量:1200 。
在這種場景下,我們決定每個檔案放 1000 條,也就有 33 個小檔案,也就有 33 個記憶體佇列,每個佇列取 Top100 條,Batch=500 時重新整理
硬碟,中轉站存放 33*2 個數字(因為入中轉站時打上了佇列標記), 最後記憶體活動最大總數為:sum=33*100+500+66=896<1200 。 時間複雜度為 N*logN 。當然這個 “閥值”,我們可以再仔細微調。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 public static void Main()       {           //生成 2^15 資料           CreateData(short.MaxValue);           //每個檔案存放 1000 條           var pageSize = 1000;           //達到 batchCount 就重新整理記錄           var batchCount = 0;           //判斷需要開啟的佇列           var pageCount = Split(pageSize);           //記憶體限制:1500 條           List> list = new List>();

          //定義一個佇列中轉器
          PriorityQueue queueControl = new PriorityQueue();

          //定義每個佇列完成狀態
          bool[] complete = new bool[pageCount];

          //佇列讀取檔案時應該跳過的記錄數
          int[] skip = new int[pageCount];

          //是否所有都完成了
          int allcomplete = 0;

          //定義 10 個佇列
          for (int i = 0; i < pageCount; i++)           {               list.Add(new PriorityQueue());

              //i:   記錄當前的佇列編碼
              //list: 佇列資料
              //skip:跳過的條數
              AddQueue(i, list, ref skip);
          }

          //初始化操作,從每個佇列中取出一條記錄,並且在入隊的過程中
          //記錄該資料所屬的 “佇列編號”
          for (int i = 0; i < list.Count; i++)           {               var temp = list[i].Dequeue();               //i: 佇列編碼,level: 要排序的資料               queueControl.Eequeue(i, temp.level);           }           //預設 500 條寫入一次檔案           List batch = new List();

          //記錄下次應該從哪一個佇列中提取資料
          int nextIndex = 0;

          while (queueControl.Count() > 0)
          {
              //從中轉器中提取資料
              var single = queueControl.Dequeue();

              //記錄下一個佇列總應該出隊的資料
              nextIndex = single.t.Value;

              var nextData = list[nextIndex].Dequeue();

              //如果改對內彈出為 null,則說明該佇列已經,需要從 nextIndex 檔案中讀取資料
              if (nextData == null)
              {
                  //如果該佇列沒有全部讀取完畢
                  if (!complete[nextIndex])
                  {
                      AddQueue(nextIndex, list, ref skip);

                      //如果從檔案中讀取還是沒有,則說明改檔案中已經沒有資料了
                      if (list[nextIndex].Count() == 0)
                      {
                          complete[nextIndex] = true;
                          allcomplete++;
                      }
                      else
                      {
                          nextData = list[nextIndex].Dequeue();
                      }
                  }
              }

              //如果彈出的數不為空,則將該數入中轉站
              if (nextData != null)
              {
                  //將要出隊的資料 轉入 中轉站
                  queueControl.Eequeue(nextIndex, nextData.level);
              }

              batch.Add(single.level);

              //如果 batch=500,或者所有的檔案都已經讀取完畢,此時我們要批次刷入資料
              if (batch.Count == batchCount || allcomplete == pageCount)
              {
                  var sw = new StreamWriter(Environment.CurrentDirectory + “//result.txt”, true);

                  foreach (var item in batch)
                  {
                      sw.WriteLine(item);
                  }

                  sw.Close();

                  batch.Clear();
              }
          }

          Console.WriteLine(“ 恭喜,外排序完畢!”);
          Console.Read();
      }

 

總的程式碼:
View Code

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Diagnostics;
6 using System.Threading;
7 using System.IO;
8 using System.Threading.Tasks;
9
10 namespace ConsoleApplication2
11 {
12 public class Program
13 {
14 public static void Main()
15 {
16 //生成 2^15 資料
17 CreateData(short.MaxValue);
18
19 //每個檔案存放 1000 條
20 var pageSize = 1000;
21
22 //達到 batchCount 就重新整理記錄
23 var batchCount = 0;
24
25 //判斷需要開啟的佇列
26 var pageCount = Split(pageSize);
27
28 //記憶體限制:1500 條
29 List> list = new List>();
30
31 //定義一個佇列中轉器
32 PriorityQueue queueControl = new PriorityQueue();
33
34 //定義每個佇列完成狀態
35 bool[] complete = new bool[pageCount];
36
37 //佇列讀取檔案時應該跳過的記錄數
38 int[] skip = new int[pageCount];
39
40 //是否所有都完成了
41 int allcomplete = 0;
42
43 //定義 10 個佇列
44 for (int i = 0; i < pageCount; i++) 45 { 46 list.Add(new PriorityQueue());
47
48 //i: 記錄當前的佇列編碼
49 //list: 佇列資料
50 //skip:跳過的條數
51 AddQueue(i, list, ref skip);
52 }
53
54 //初始化操作,從每個佇列中取出一條記錄,並且在入隊的過程中
55 //記錄該資料所屬的 “佇列編號”
56 for (int i = 0; i < list.Count; i++) 57 { 58 var temp = list[i].Dequeue(); 59 60 //i: 佇列編碼,level: 要排序的資料 61 queueControl.Eequeue(i, temp.level); 62 } 63 64 //預設 500 條寫入一次檔案 65 List batch = new List();
66
67 //記錄下次應該從哪一個佇列中提取資料
68 int nextIndex = 0;
69
70 while (queueControl.Count() > 0)
71 {
72 //從中轉器中提取資料
73 var single = queueControl.Dequeue();
74
75 //記錄下一個佇列總應該出隊的資料
76 nextIndex = single.t.Value;
77
78 var nextData = list[nextIndex].Dequeue();
79
80 //如果改對內彈出為 null,則說明該佇列已經,需要從 nextIndex 檔案中讀取資料
81 if (nextData == null)
82 {
83 //如果該佇列沒有全部讀取完畢
84 if (!complete[nextIndex])
85 {
86 AddQueue(nextIndex, list, ref skip);
87
88 //如果從檔案中讀取還是沒有,則說明改檔案中已經沒有資料了
89 if (list[nextIndex].Count() == 0)
90 {
91 complete[nextIndex] = true;
92 allcomplete++;
93 }
94 else
95 {
96 nextData = list[nextIndex].Dequeue();
97 }
98 }
99 }
100
101 //如果彈出的數不為空,則將該數入中轉站
102 if (nextData != null)
103 {
104 //將要出隊的資料 轉入 中轉站
105 queueControl.Eequeue(nextIndex, nextData.level);
106 }
107
108 batch.Add(single.level);
109
110 //如果 batch=500,或者所有的檔案都已經讀取完畢,此時我們要批次刷入資料
111 if (batch.Count == batchCount || allcomplete == pageCount)
112 {
113 var sw = new StreamWriter(Environment.CurrentDirectory + “//result.txt”, true);
114
115 foreach (var item in batch)
116 {
117 sw.WriteLine(item);
118 }
119
120 sw.Close();
121
122 batch.Clear();
123 }
124 }
125
126 Console.WriteLine(“ 恭喜,外排序完畢!”);
127 Console.Read();
128 }
129
130 #region 將資料加入指定編號佇列
131 ///

132 /// 將資料加入指定編號佇列
133 ///

134 /// 佇列編號 135 /// 檔案中跳過的條數 136 /// 137 /// 需要每次讀取的條數 138 public static void AddQueue(int i, List> list, ref int[] skip, int top = 100)
139 {
140 var result = File.ReadAllLines((Environment.CurrentDirectory + “//” + (i + 1) + “.txt”))
141 .Skip(skip[i]).Take(top).Select(j => Convert.ToInt32(j));
142
143 //加入到集合中
144 foreach (var item in result)
145 list[i].Eequeue(null, item);
146
147 //將個數累計到 skip 中,表示下次要跳過的記錄數
148 skip[i] += result.Count();
149 }
150 #endregion
151
152 #region 隨機生成資料
153 ///

154 /// 隨機生成資料
155 ///執行生成的資料上線 156 ///

157 public static void CreateData(int max)
158 {
159 var sw = new StreamWriter(Environment.CurrentDirectory + “//demo.txt”);
160
161 for (int i = 0; i < max; i++) 162 { 163 Thread.Sleep(2); 164 var rand = new Random((int)DateTime.Now.Ticks).Next(0, int.MaxValue >> 3);
165
166 sw.WriteLine(rand);
167 }
168 sw.Close();
169 }
170 #endregion
171
172 #region 將資料進行分份
173 ///

174 /// 將資料進行分份
175 /// 每頁要顯示的條數 176 ///

177 public static int Split(int size)
178 {
179 //檔案總記錄數
180 int totalCount = 0;
181
182 //每一份檔案存放 size 條 記錄
183 List small = new List();
184
185 var sr = new StreamReader((Environment.CurrentDirectory + “//demo.txt”));
186
187 var pageSize = size;
188
189 int pageCount = 0;
190
191 int pageIndex = 0;
192
193 while (true)
194 {
195 var line = sr.ReadLine();
196
197 if (!string.IsNullOrEmpty(line))
198 {
199 totalCount++;
200
201 //加入小集合中
202 small.Add(Convert.ToInt32(line));
203
204 //說明已經到達指定的 size 條數了
205 if (totalCount % pageSize == 0)
206 {
207 pageIndex = totalCount / pageSize;
208
209 small = small.OrderBy(i => i).Select(i => i).ToList();
210
211 File.WriteAllLines(Environment.CurrentDirectory + “//” + pageIndex + “.txt”, small.Select(i => i.ToString()));
212
213 small.Clear();
214 }
215 }
216 else
217 {
218 //說明已經讀完了,將剩餘的 small 記錄寫入到檔案中
219 pageCount = (int)Math.Ceiling((double)totalCount / pageSize);
220
221 small = small.OrderBy(i => i).Select(i => i).ToList();
222
223 File.WriteAllLines(Environment.CurrentDirectory + “//” + pageCount + “.txt”, small.Select(i => i.ToString()));
224
225 break;
226 }
227 }
228
229 return pageCount;
230 }
231 #endregion
232 }
233 }

 
優先佇列:
View Code

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Diagnostics;
6 using System.Threading;
7 using System.IO;
8
9 namespace ConsoleApplication2
10 {
11 public class PriorityQueue
12 {
13 ///

14 /// 定義一個陣列來存放節點
15 ///

16 private List nodeList = new List();
17
18 #region 堆節點定義
19 ///

20 /// 堆節點定義
21 ///

22 public class HeapNode
23 {
24 ///

25 /// 實體資料
26 ///

27 public T t { get; set; }
28
29 ///

30 /// 優先順序別 1-10 個級別 (優先順序別遞增)
31 ///

32 public int level { get; set; }
33
34 public HeapNode(T t, int level)
35 {
36 this.t = t;
37 this.level = level;
38 }
39
40 public HeapNode() { }
41 }
42 #endregion
43
44 #region 新增操作
45 ///

46 /// 新增操作
47 ///

48 public void Eequeue(T t, int level = 1)
49 {
50 //將當前節點追加到堆尾
51 nodeList.Add(new HeapNode(t, level));
52
53 //如果只有一個節點,則不需要進行篩操作
54 if (nodeList.Count == 1)
55 return;
56
57 //獲取最後一個非葉子節點
58 int parent = nodeList.Count / 2 – 1;
59
60 //堆調整
61 UpHeapAdjust(nodeList, parent);
62 }
63 #endregion
64
65 #region 對堆進行上濾操作,使得滿足堆性質
66 ///

67 /// 對堆進行上濾操作,使得滿足堆性質
68 ///

69 /// 70 /// 非葉子節點的之後指標(這裡要注意:我們
71 /// 的篩操作時針對非葉節點的)
72 /// 73 public void UpHeapAdjust(List nodeList, int parent)
74 {
75 while (parent >= 0)
76 {
77 //當前 index 節點的左孩子
78 var left = 2 * parent + 1;
79
80 //當前 index 節點的右孩子
81 var right = left + 1;
82
83 //parent 子節點中最大的孩子節點,方便於 parent 進行比較
84 //預設為 left 節點
85 var min = left;
86
87 //判斷當前節點是否有右孩子
88 if (right < nodeList.Count) 89 { 90 //判斷 parent 要比較的最大子節點 91 min = nodeList[left].level < nodeList[right].level ? left : right; 92 } 93 94 //如果parent節點大於它的某個子節點的話,此時篩操作 95 if (nodeList[parent].level > nodeList[min].level)
96 {
97 //子節點和父節點進行交換操作
98 var temp = nodeList[parent];
99 nodeList[parent] = nodeList[min];
100 nodeList[min] = temp;
101
102 //繼續進行更上一層的過濾
103 parent = (int)Math.Ceiling(parent / 2d) – 1;
104 }
105 else
106 {
107 break;
108 }
109 }
110 }
111 #endregion
112
113 #region 優先佇列的出隊操作
114 ///

115 /// 優先佇列的出隊操作
116 ///

117 ///
118 public HeapNode Dequeue()
119 {
120 if (nodeList.Count == 0)
121 return null;
122
123 //出佇列操作,彈出資料頭元素
124 var pop = nodeList[0];
125
126 //用尾元素填充頭元素
127 nodeList[0] = nodeList[nodeList.Count – 1];
128
129 //刪除尾節點
130 nodeList.RemoveAt(nodeList.Count – 1);
131
132 //然後從根節點下濾堆
133 DownHeapAdjust(nodeList, 0);
134
135 return pop;
136 }
137 #endregion
138
139 #region 對堆進行下濾操作,使得滿足堆性質
140 ///

141 /// 對堆進行下濾操作,使得滿足堆性質
142 ///

143 /// 144 /// 非葉子節點的之後指標(這裡要注意:我們
145 /// 的篩操作時針對非葉節點的)
146 /// 147 public void DownHeapAdjust(List nodeList, int parent)
148 {
149 while (2 * parent + 1 < nodeList.Count) 150 { 151 //當前 index 節點的左孩子 152 var left = 2 * parent + 1; 153 154 //當前 index 節點的右孩子 155 var right = left + 1; 156 157 //parent 子節點中最大的孩子節點,方便於 parent 進行比較 158 //預設為 left 節點 159 var min = left; 160 161 //判斷當前節點是否有右孩子 162 if (right < nodeList.Count) 163 { 164 //判斷 parent 要比較的最大子節點 165 min = nodeList[left].level < nodeList[right].level ? left : right; 166 } 167 168 //如果parent節點小於它的某個子節點的話,此時篩操作 169 if (nodeList[parent].level > nodeList[min].level)
170 {
171 //子節點和父節點進行交換操作
172 var temp = nodeList[parent];
173 nodeList[parent] = nodeList[min];
174 nodeList[min] = temp;
175
176 //繼續進行更下一層的過濾
177 parent = min;
178 }
179 else
180 {
181 break;
182 }
183 }
184 }
185 #endregion
186
187 #region 獲取元素並下降到指定的 level 級別
188 ///

189 /// 獲取元素並下降到指定的 level 級別
190 ///

191 ///
192 public HeapNode GetAndDownPriority(int level)
193 {
194 if (nodeList.Count == 0)
195 return null;
196
197 //獲取頭元素
198 var pop = nodeList[0];
199
200 //設定指定優先順序(如果為 MinValue 則為 — 操作)
201 nodeList[0].level = level == int.MinValue ? –nodeList[0].level : level;
202
203 //下濾堆
204 DownHeapAdjust(nodeList, 0);
205
206 return nodeList[0];
207 }
208 #endregion
209
210 #region 獲取元素並下降優先順序
211 ///

212 /// 獲取元素並下降優先順序
213 ///

214 ///
215 public HeapNode GetAndDownPriority()
216 {
217 //下降一個優先順序
218 return GetAndDownPriority(int.MinValue);
219 }
220 #endregion
221
222 #region 返回當前優先佇列中的元素個數
223 ///

224 /// 返回當前優先佇列中的元素個數
225 ///

226 ///
227 public int Count()
228 {
229 return nodeList.Count;
230 }
231 #endregion
232 }
233 }

轉載在網際網路部落格網站,版權歸作者所有, 原文連結:http://www.cnblogs.com/huangxincheng/archive/2012/12/19/2824943.html