Skip to content

Commit 946139d

Browse files
authored
Update: Change QuickSort to QuickSelect for getting nth element (#8)
1 parent 14deee0 commit 946139d

File tree

1 file changed

+26
-25
lines changed

1 file changed

+26
-25
lines changed

Kdtree/Source/Kdtree/Private/KdtreeInternal.cpp

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -24,46 +24,47 @@ void Swap(T* Var1, T* Var2)
2424
}
2525

2626
template <typename T>
27-
void QuickSort(T* First, T* Last, TFunctionRef<int(T, T)> Comparator)
27+
void QuickSelect(T* First, T* Nth, T* Last, TFunctionRef<int(T, T)> Comparator)
2828
{
29-
T* Left = First;
30-
T* Right = Last;
31-
T Pivot = *First;
32-
3329
while (true)
3430
{
35-
while (Left <= Last && Comparator(*Left, Pivot) == 1)
31+
T* Pivot = First;
32+
T* Left = First + 1;
33+
T* Right = Last - 1;
34+
35+
while (Left <= Right)
3636
{
37-
Left++;
37+
while (Left <= Right && Comparator(*Left, *Pivot) == 1) Left++;
38+
while (Left <= Right && Comparator(*Right, *Pivot) == -1) Right--;
39+
if (Left <= Right)
40+
{
41+
Swap(Left, Right);
42+
Left++;
43+
Right--;
44+
}
3845
}
39-
while (Right >= First && Comparator(*Right, Pivot) == -1)
46+
47+
Swap(Pivot, Right);
48+
49+
if (Right == Nth)
4050
{
41-
Right--;
51+
break;
4252
}
43-
if (Left > Right)
53+
else if (Nth < Right)
4454
{
45-
break;
55+
Last = Right;
56+
}
57+
else
58+
{
59+
First = Left;
4660
}
47-
Swap(Left, Right);
48-
Left++;
49-
Right--;
50-
}
51-
52-
if (First < Left - 1)
53-
{
54-
QuickSort(First, Left - 1, Comparator);
55-
}
56-
if (Left < Last)
57-
{
58-
QuickSort(Left, Last, Comparator);
5961
}
6062
}
6163

6264
template <typename T>
6365
void NthElement(T* First, T* Nth, T* Last, TFunctionRef<int(T, T)> Comparator)
6466
{
65-
// TODO: Use faster algorithm such as introselect.
66-
QuickSort(First, Last - 1, Comparator);
67+
QuickSelect(First, Nth, Last, Comparator);
6768
}
6869

6970
FKdtreeNode* BuildNode(const FKdtreeInternal& Tree, int* Indices, int NumData, int Depth)

0 commit comments

Comments
 (0)