-
Notifications
You must be signed in to change notification settings - Fork 1
/
QuickSelect.cs
63 lines (52 loc) · 1.84 KB
/
QuickSelect.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
using AlgorithmsAndDataStructures.Algorithms.Sorting;
namespace AlgorithmsAndDataStructures.Algorithms.Search
{
public class QuickSelect
{
#pragma warning disable CA1822 // Mark members as static
public int GetLargestElement(int[] input, int target)
#pragma warning restore CA1822 // Mark members as static
{
return input is null ? default : GetLargestElementInternal(input, 0, input.Length - 1, target);
}
private static int GetLargestElementInternal(int[] input, int start, int end, int target)
{
if (start == end && start == target)
{
return input[target];
}
var pivot = Partition(input, start, end);
if (pivot == target)
{
return input[target];
}
if (pivot > target)
{
return GetLargestElementInternal(input, start, pivot, target);
}
return GetLargestElementInternal(input, pivot + 1, end, target);
}
private static int Partition(int[] input, int start, int end)
{
var mid = start + ((end - start) / 2);
var leftPointer = start - 1;
var rightPointer = end + 1;
while (true)
{
do
{
leftPointer++;
} while (input[leftPointer] < input[mid]);
do
{
rightPointer--;
} while (input[rightPointer] > input[mid]);
if (rightPointer <= leftPointer)
{
return rightPointer;
}
SortUtilities.Swap(input, leftPointer, rightPointer);
}
}
}
}