-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSelection.cs
More file actions
76 lines (66 loc) · 2.46 KB
/
QuickSelection.cs
File metadata and controls
76 lines (66 loc) · 2.46 KB
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
using System;
namespace DA.Algorithms.Sorting
{
public static class QuickSelection
{
/// <summary>
/// Find the element, which will be at the K-th position without actually sorting the whole collection.
/// <para>Time Complexity - O(log n)</para>
/// </summary>
/// <typeparam name="T">Type of an array</typeparam>
/// <param name="array">A collection with an elements</param>
/// <param name="position">Index of the requested element.</param>
public static T GetElement<T> (T[] array, int position) where T : IComparable<T>
{
QuickSelect (array, 0, array.Length - 1, position);
return array[position];
}
/// <summary>
/// Quick select is used to find the element, which will be at the K-th position without actually sorting the whole collection.
/// <para>Time Complexity - O(log n)</para>
/// </summary>
/// <typeparam name="T">Type of an array</typeparam>
/// <param name="array">A collection with an elements</param>
/// <param name="k">Index of the requested element.</param>
public static void QuickSelect<T> (T[] array, int lower, int upper, int k) where T : IComparable<T>
{
if (upper <= lower) return;
T pivot = array[lower];
int startIndex = lower;
int stopIndex = upper;
while (lower < upper)
{
while (array[lower].CompareTo(pivot) <= 0 && lower < upper)
{
++lower;
}
while (array[upper].CompareTo(pivot) > 0 && lower <= upper)
{
--upper;
}
if (lower < upper)
{
Swap (array, lower, upper);
}
Swap (array, upper, startIndex);
if (k < upper)
{
QuickSelect (array, startIndex, upper - 1, k);
}
if (k > upper)
{
QuickSelect (array, upper + 1, stopIndex, k);
}
}
}
/// <summary>
/// Swap two elements of an array.
/// </summary>
private static void Swap<T> (T[] array, int first, int second)
{
T temp = array[first];
array[first] = array[second];
array[second] = temp;
}
}
}