Skip to content

Changed the original QuickSort to QuickSelect #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions Kdtree/Source/Kdtree/Private/KdtreeInternal.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,46 +24,47 @@ void Swap(T* Var1, T* Var2)
}

template <typename T>
void QuickSort(T* First, T* Last, TFunctionRef<int(T, T)> Comparator)
void QuickSelect(T* First, T* Nth, T* Last, TFunctionRef<int(T, T)> Comparator)
{
T* Left = First;
T* Right = Last;
T Pivot = *First;

while (true)
{
while (Left <= Last && Comparator(*Left, Pivot) == 1)
T* Pivot = First;
T* Left = First + 1;
T* Right = Last - 1;

while (Left <= Right)
{
Left++;
while (Left <= Right && Comparator(*Left, *Pivot) == 1) Left++;
while (Left <= Right && Comparator(*Right, *Pivot) == -1) Right--;
if (Left <= Right)
{
Swap(Left, Right);
Left++;
Right--;
}
}
while (Right >= First && Comparator(*Right, Pivot) == -1)

Swap(Pivot, Right);

if (Right == Nth)
{
Right--;
break;
}
if (Left > Right)
else if (Nth < Right)
{
break;
Last = Right;
}
else
{
First = Left;
}
Swap(Left, Right);
Left++;
Right--;
}

if (First < Left - 1)
{
QuickSort(First, Left - 1, Comparator);
}
if (Left < Last)
{
QuickSort(Left, Last, Comparator);
}
}

template <typename T>
void NthElement(T* First, T* Nth, T* Last, TFunctionRef<int(T, T)> Comparator)
{
// TODO: Use faster algorithm such as introselect.
QuickSort(First, Last - 1, Comparator);
QuickSelect(First, Nth, Last, Comparator);
}

FKdtreeNode* BuildNode(const FKdtreeInternal& Tree, int* Indices, int NumData, int Depth)
Expand Down
Loading