forked from abdonkov/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ParallelMergeSorter.LinkedList.cs
599 lines (529 loc) · 32.7 KB
/
ParallelMergeSorter.LinkedList.cs
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace DSA.Algorithms.Sorting
{
public static partial class ParallelMergeSorter
{
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in ascending order using the default comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSort<T>(this LinkedList<T> list)
{
return ParallelMergeSort(list, Comparer<T>.Default);
}
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in descending order using the default comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSortDescending<T>(this LinkedList<T> list)
{
return ParallelMergeSortDescending(list, Comparer<T>.Default);
}
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in ascending order using the specified comparison.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="comparison">The <see cref="Comparison{T}"/> used for comparing the elements.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSort<T>(this LinkedList<T> list, Comparison<T> comparison)
{
if (comparison == null) throw new ArgumentNullException("comparison");
return ParallelMergeSort(list, Comparer<T>.Create(comparison));
}
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in descending order using the specified comparison.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="comparison">The <see cref="Comparison{T}"/> used for comparing the elements.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSortDescending<T>(this LinkedList<T> list, Comparison<T> comparison)
{
if (comparison == null) throw new ArgumentNullException("comparison");
return ParallelMergeSortDescending(list, Comparer<T>.Create(comparison));
}
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in ascending order using the specified comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSort<T>(this LinkedList<T> list, IComparer<T> comparer)
{
if (list.Count > 0)
return ParallelMergeSort(list, list.First, list.Last, comparer);
else
return list;
}
/// <summary>
/// Sorts the elements in the entire <see cref="LinkedList{T}"/> in descending order using the specified comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSortDescending<T>(this LinkedList<T> list, IComparer<T> comparer)
{
if (list.Count > 0)
return ParallelMergeSortDescending(list, list.First, list.Last, comparer);
else
return list;
}
/// <summary>
/// Sorts a range of elements in the <see cref="LinkedList{T}"/> in ascending order using the specified comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="index">The zero-based starting index of the range for sorting.</param>
/// <param name="count">The length of the range for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSort<T>(this LinkedList<T> list, int index, int count, IComparer<T> comparer)
{
if (index < 0 || index >= list.Count) throw new ArgumentOutOfRangeException("index");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (index + count > list.Count) throw new ArgumentException("Invalid length specified.");
if (comparer == null) comparer = Comparer<T>.Default;
LinkedListNode<T> startNode = null;
LinkedListNode<T> endNode = null;
int curNodeIndex = 0;
int nodesTraversedAfterStartNode = 0;
var curNode = list.First;
while (curNode != null)
{
// if we at the node on the given index save the start node
if (curNodeIndex == index)
startNode = curNode;
// if we are at the node or after the given index, increment the node counter
if (curNodeIndex >= index)
nodesTraversedAfterStartNode++;
// if we traversed enought nodes as the given count save the end node and break
if (nodesTraversedAfterStartNode == count)
{
endNode = curNode;
break;
}
// go onwards
curNodeIndex++;
curNode = curNode.Next;
}
return ParallelMergeSort(list, startNode, endNode, comparer);
}
/// <summary>
/// Sorts a range of elements in the <see cref="LinkedList{T}"/> in descending order using the specified comparer.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="index">The zero-based starting index of the range for sorting.</param>
/// <param name="count">The length of the range for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSortDescending<T>(this LinkedList<T> list, int index, int count, IComparer<T> comparer)
{
if (index < 0 || index >= list.Count) throw new ArgumentOutOfRangeException("index");
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (index + count > list.Count) throw new ArgumentException("Invalid length specified.");
if (comparer == null) comparer = Comparer<T>.Default;
LinkedListNode<T> startNode = null;
LinkedListNode<T> endNode = null;
int curNodeIndex = 0;
int nodesTraversedAfterStartNode = 0;
var curNode = list.First;
while (curNode != null)
{
// if we at the node on the given index save the start node
if (curNodeIndex == index)
startNode = curNode;
// if we are at the node or after the given index, increment the node counter
if (curNodeIndex >= index)
nodesTraversedAfterStartNode++;
// if we traversed enought nodes as the given count save the end node and break
if (nodesTraversedAfterStartNode == count)
{
endNode = curNode;
break;
}
// go onwards
curNodeIndex++;
curNode = curNode.Next;
}
return ParallelMergeSortDescending(list, startNode, endNode, comparer);
}
/// <summary>
/// Sorts a range of elements in the <see cref="LinkedList{T}"/> in ascending order using the specified comparer beginning from the start node and ending at the end node.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the range for sorting.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the range for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSort<T>(this LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, IComparer<T> comparer)
{
if (startNode == null) throw new ArgumentNullException("startNode");
if (endNode == null) throw new ArgumentNullException("endNode");
if (startNode.List != list) throw new ArgumentException("startNode doesn't belong to the list!");
if (endNode.List != list) throw new ArgumentException("startNode doesnt't belong to the list!");
if (comparer == null) comparer = Comparer<T>.Default;
int depth = Environment.ProcessorCount;
if (list.Last == endNode)// the end node is the last in the list
ParallelSplitMerge(list, startNode, endNode, null, depth, comparer);// the node after it is null
else
ParallelSplitMerge(list, startNode, endNode, endNode.Next, depth, comparer);
return list;
}
/// <summary>
/// Parallel algorithm. In-place sorting of the given <see cref="LinkedList{T}"/> elements. Used for ascending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="depthRemaining">The remaining depth of the recursion for which parallel tasks are invoked.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
private static void ParallelSplitMerge<T>(LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, LinkedListNode<T> nodeAfterEndNode, int depthRemaining, IComparer<T> comparer)
{
// End of recursion. If we have 1 item or less we consider it sorted
if (list.Count < 2) return;
// spliting the list into two lists
var left = new LinkedList<T>();
var right = new LinkedList<T>();
var curNode = startNode;
int i = 0;
int leftItemsNumber = list.Count / 2;
while (curNode != nodeAfterEndNode)
{
if (i++ < leftItemsNumber)
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the curent node from the list
left.AddLast(node);// add the saved node to the left list
}
else
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the current node from the list
right.AddLast(node);// add the saved node to the right list
}
}
// Recursively sort both sublists
// NOTE: node after endNode is null because in the left and right splits
// we work with all nodes from the list.
// if depth is low enough, we create new tasks for the spliting
if (depthRemaining > 0)
{
Parallel.Invoke
(
() => ParallelSplitMerge(left, left.First, left.Last, null, depthRemaining - 1, comparer),
() => ParallelSplitMerge(right, right.First, right.Last, null, depthRemaining - 1, comparer)
);
}
else // if max depth level is exceeded we continue with sequential spliting
{
SequentialSplitMerge(left, left.First, left.Last, null, comparer);
SequentialSplitMerge(right, right.First, right.Last, null, comparer);
}
// Merge the two splits into the given list
Merge(list, left, right, nodeAfterEndNode, comparer);
// NOTE: only the last merging of two lists is done on the given list for sorting
}
/// <summary>
/// Sequential algorithm. In-place sorting of the given <see cref="LinkedList{T}"/> elements. Used for ascending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
private static void SequentialSplitMerge<T>(LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, LinkedListNode<T> nodeAfterEndNode, IComparer<T> comparer)
{
// End of recursion. If we have 1 item or less we consider it sorted
if (list.Count < 2) return;
// spliting the list into two lists
var left = new LinkedList<T>();
var right = new LinkedList<T>();
var curNode = startNode;
int i = 0;
int leftItemsNumber = list.Count / 2;
while (curNode != nodeAfterEndNode)
{
if (i++ < leftItemsNumber)
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the curent node from the list
left.AddLast(node);// add the saved node to the left list
}
else
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the current node from the list
right.AddLast(node);// add the saved node to the right list
}
}
// Recursively sort both sublists
// NOTE: node after endNode is null because in the left and right splits
// we work with all nodes from the list.
SequentialSplitMerge(left, left.First, left.Last, null, comparer);
SequentialSplitMerge(right, right.First, right.Last, null, comparer);
// Merge the two splits into the given list
Merge(list, left, right, nodeAfterEndNode, comparer);
// NOTE: only the last merging of two lists is done on the given list for sorting
}
/// <summary>
/// Merging two lists into a given <see cref="LinkedList{T}"/>. Used for ascending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="mergeList">The <see cref="LinkedList{T}"/> for merging the left and right lists into.</param>
/// <param name="left">The left <see cref="LinkedList{T}"/> containing some of the elements for sorting.</param>
/// <param name="right">The right <see cref="LinkedList{T}"/> containing some of the elements for sorting.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> for the merged elements from the left <see cref="LinkedList{T}"/> and right <see cref="LinkedList{T}"/>.</returns>
private static void Merge<T>(LinkedList<T> mergeList, LinkedList<T> left, LinkedList<T> right, LinkedListNode<T> nodeAfterEndNode, IComparer<T> comparer)
{
bool nodeAfterEndNodeIsNull = nodeAfterEndNode == null;
// merging until one of the lists becomes empty
while (left.Count > 0 && right.Count > 0)
{
if (comparer.Compare(left.First.Value, right.First.Value) <= 0)
{
var node = left.First;
left.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
else
{
var node = right.First;
right.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
}
// add the remaining elements from the left or the right list
while (left.Count > 0)
{
var node = left.First;
left.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
while (right.Count > 0)
{
var node = right.First;
right.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
}
/// <summary>
/// Sorts a range of elements in the <see cref="LinkedList{T}"/> in descending order using the specified comparer beginning from the start node and ending at the end node.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the range for sorting.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the range for sorting.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements,
/// or null to use the default comparer <see cref="Comparer{T}.Default"/>.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> when sorted.</returns>
public static LinkedList<T> ParallelMergeSortDescending<T>(this LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, IComparer<T> comparer)
{
if (startNode == null) throw new ArgumentNullException("startNode");
if (endNode == null) throw new ArgumentNullException("endNode");
if (startNode.List != list) throw new ArgumentException("startNode doesn't belong to the list!");
if (endNode.List != list) throw new ArgumentException("startNode doesnt't belong to the list!");
if (comparer == null) comparer = Comparer<T>.Default;
int depth = Environment.ProcessorCount;
if (list.Last == endNode)// the end node is the last in the list
ParallelSplitMergeDescending(list, startNode, endNode, null, depth, comparer);// the node after it is null
else
ParallelSplitMergeDescending(list, startNode, endNode, endNode.Next, depth, comparer);
return list;
}
/// <summary>
/// Parallel algorithm. In-place sorting of the given <see cref="LinkedList{T}"/> elements. Used for descending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="depthRemaining">The remaining depth of the recursion for which parallel tasks are invoked.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
private static void ParallelSplitMergeDescending<T>(LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, LinkedListNode<T> nodeAfterEndNode, int depthRemaining, IComparer<T> comparer)
{
// End of recursion. If we have 1 item or less we consider it sorted
if (list.Count < 2) return;
// spliting the list into two lists
var left = new LinkedList<T>();
var right = new LinkedList<T>();
var curNode = startNode;
int i = 0;
int leftItemsNumber = list.Count / 2;
while (curNode != nodeAfterEndNode)
{
if (i++ < leftItemsNumber)
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the curent node from the list
left.AddLast(node);// add the saved node to the left list
}
else
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the current node from the list
right.AddLast(node);// add the saved node to the right list
}
}
// Recursively sort both sublists
// NOTE: node after endNode is null because in the left and right splits
// we work with all nodes from the list.
// if depth is low enough, we create new tasks for the spliting
if (depthRemaining > 0)
{
Parallel.Invoke
(
() => ParallelSplitMergeDescending(left, left.First, left.Last, null, depthRemaining - 1, comparer),
() => ParallelSplitMergeDescending(right, right.First, right.Last, null, depthRemaining - 1, comparer)
);
}
else // if max depth level is exceeded we continue with sequential spliting
{
SequentialSplitMergeDescending(left, left.First, left.Last, null, comparer);
SequentialSplitMergeDescending(right, right.First, right.Last, null, comparer);
}
// Merge the two splits into the given list
MergeDescending(list, left, right, nodeAfterEndNode, comparer);
// NOTE: only the last merging of two lists is done on the given list for sorting
}
/// <summary>
/// Sequential algorithm. In-place sorting of the given <see cref="LinkedList{T}"/> elements. Used for descending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="list">The <see cref="LinkedList{T}"/> containing the elements for sorting.</param>
/// <param name="startNode">The start <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="endNode">The end <see cref="LinkedListNode{T}"/> of the current split.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
private static void SequentialSplitMergeDescending<T>(LinkedList<T> list, LinkedListNode<T> startNode, LinkedListNode<T> endNode, LinkedListNode<T> nodeAfterEndNode, IComparer<T> comparer)
{
// End of recursion. If we have 1 item or less we consider it sorted
if (list.Count < 2) return;
// spliting the list into two lists
var left = new LinkedList<T>();
var right = new LinkedList<T>();
var curNode = startNode;
int i = 0;
int leftItemsNumber = list.Count / 2;
while (curNode != nodeAfterEndNode)
{
if (i++ < leftItemsNumber)
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the curent node from the list
left.AddLast(node);// add the saved node to the left list
}
else
{
var node = curNode;// save the current node
curNode = curNode.Next;// go to the next node
list.Remove(node);// remove the current node from the list
right.AddLast(node);// add the saved node to the right list
}
}
// Recursively sort both sublists
// NOTE: node after endNode is null because in the left and right splits
// we work with all nodes from the list.
SequentialSplitMergeDescending(left, left.First, left.Last, null, comparer);
SequentialSplitMergeDescending(right, right.First, right.Last, null, comparer);
// Merge the two splits into the given list
MergeDescending(list, left, right, nodeAfterEndNode, comparer);
// NOTE: only the last merging of two lists is done on the given list for sorting
}
/// <summary>
/// Merging two lists into a given <see cref="LinkedList{T}"/>. Used for descending sort.
/// </summary>
/// <typeparam name="T">The data type of the <see cref="LinkedList{T}"/>.</typeparam>
/// <param name="mergeList">The <see cref="LinkedList{T}"/> for merging the left and right lists into.</param>
/// <param name="left">The left <see cref="LinkedList{T}"/> containing some of the elements for sorting.</param>
/// <param name="right">The right <see cref="LinkedList{T}"/> containing some of the elements for sorting.</param>
/// <param name="nodeAfterEndNode">The <see cref="LinkedListNode{T}"/> which is the node after the sorted sequence.</param>
/// <param name="comparer">The <see cref="IComparable{T}"/> implementation used for comparing the elements.</param>
/// <returns>Returns the given <see cref="LinkedList{T}"/> for the merged elements from the left <see cref="LinkedList{T}"/> and right <see cref="LinkedList{T}"/>.</returns>
private static void MergeDescending<T>(LinkedList<T> mergeList, LinkedList<T> left, LinkedList<T> right, LinkedListNode<T> nodeAfterEndNode, IComparer<T> comparer)
{
bool nodeAfterEndNodeIsNull = nodeAfterEndNode == null;
// merging until one of the lists becomes empty
while (left.Count > 0 && right.Count > 0)
{
if (comparer.Compare(left.First.Value, right.First.Value) >= 0)
{
var node = left.First;
left.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
else
{
var node = right.First;
right.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
}
// add the remaining elements from the left or the right list
while (left.Count > 0)
{
var node = left.First;
left.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
while (right.Count > 0)
{
var node = right.First;
right.RemoveFirst();
if (nodeAfterEndNodeIsNull)// if the end node is the last in the list
mergeList.AddLast(node);// we add at the end of the list
else// if the end node is not the last
mergeList.AddBefore(nodeAfterEndNode, node);// we add before the node which is after the end node
}
}
}
}