Trying to determine if I should be using NativeList.Sort() in an algorithm or not, but I’m not sure what this does under the hood or how expensive it is. Does anyone know?
EDIT: wow, sorry, found it within seconds of posting thread. I thought I couldn’t find it. My bad
Sort
const int k_IntrosortSizeThreshold = 16;
unsafe static void IntroSort<T, U>(void* array, int lo, int hi, int depth, U comp) where T : struct where U : IComparer<T>
{
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= k_IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems<T, U>(array, lo, hi - 1, comp);
SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
SwapIfGreaterWithItems<T, U>(array, hi - 1, hi, comp);
return;
}
InsertionSort<T, U>(array, lo, hi, comp);
return;
}
if (depth == 0)
{
HeapSort<T, U>(array, lo, hi, comp);
return;
}
depth--;
int p = Partition<T, U>(array, lo, hi, comp);
IntroSort<T, U>(array, p + 1, hi, depth, comp);
hi = p - 1;
}
}
unsafe static void InsertionSort<T, U>(void* array, int lo, int hi, U comp) where T : struct where U : IComparer<T>
{
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = UnsafeUtility.ReadArrayElement<T>(array, i + 1);
while (j >= lo && comp.Compare(t, UnsafeUtility.ReadArrayElement<T>(array, j)) < 0)
{
UnsafeUtility.WriteArrayElement<T>(array, j + 1, UnsafeUtility.ReadArrayElement<T>(array, j));
j--;
}
UnsafeUtility.WriteArrayElement<T>(array, j + 1, t);
}
}
unsafe static int Partition<T, U>(void* array, int lo, int hi, U comp) where T : struct where U : IComparer<T>
{
int mid = lo + ((hi - lo) / 2);
SwapIfGreaterWithItems<T, U>(array, lo, mid, comp);
SwapIfGreaterWithItems<T, U>(array, lo, hi, comp);
SwapIfGreaterWithItems<T, U>(array, mid, hi, comp);
T pivot = UnsafeUtility.ReadArrayElement<T>(array, mid);
Swap<T>(array, mid, hi - 1);
int left = lo, right = hi - 1;
while (left < right)
{
while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, ++left)) > 0) ;
while (comp.Compare(pivot, UnsafeUtility.ReadArrayElement<T>(array, --right)) < 0) ;
if (left >= right)
break;
Swap<T>(array, left, right);
}
Swap<T>(array, left, (hi - 1));
return left;
}