forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MedianOfThreeQuickSorter.cs
55 lines (46 loc) · 1.29 KB
/
MedianOfThreeQuickSorter.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
using System.Collections.Generic;
namespace Algorithms.Sorters.Comparison;
/// <summary>
/// Sorts arrays using quicksort (selecting median of three as a pivot).
/// </summary>
/// <typeparam name="T">Type of array element.</typeparam>
public sealed class MedianOfThreeQuickSorter<T> : QuickSorter<T>
{
protected override T SelectPivot(T[] array, IComparer<T> comparer, int left, int right)
{
var leftPoint = array[left];
var middlePoint = array[left + (right - left) / 2];
var rightPoint = array[right];
return FindMedian(comparer, leftPoint, middlePoint, rightPoint);
}
private static T FindMedian(IComparer<T> comparer, T a, T b, T c)
{
if (comparer.Compare(a, b) <= 0)
{
// a <= b <= c
if (comparer.Compare(b, c) <= 0)
{
return b;
}
// a <= c < b
if (comparer.Compare(a, c) <= 0)
{
return c;
}
// c < a <= b
return a;
}
// a > b >= c
if (comparer.Compare(b, c) >= 0)
{
return b;
}
// a >= c > b
if (comparer.Compare(a, c) >= 0)
{
return c;
}
// c > a > b
return a;
}
}