DotRecastNetSim/src/DotRecast.Core/CollectionExtensions.cs

50 lines
1.5 KiB
C#
Raw Normal View History

2023-03-14 08:02:43 +03:00
using System;
using System.Collections.Generic;
2023-03-16 19:09:10 +03:00
namespace DotRecast.Core
{
2023-03-16 19:48:49 +03:00
public static class CollectionExtensions
2023-03-14 08:02:43 +03:00
{
2023-07-25 09:44:57 +03:00
/// Sorts the given data in-place using insertion sort.
///
/// @param data The data to sort
/// @param dataLength The number of elements in @p data
public static void InsertSort(this int[] data)
{
for (int valueIndex = 1; valueIndex < data.Length; valueIndex++)
{
int value = data[valueIndex];
int insertionIndex;
for (insertionIndex = valueIndex - 1; insertionIndex >= 0 && data[insertionIndex] > value; insertionIndex--)
{
// Shift over values
data[insertionIndex + 1] = data[insertionIndex];
}
// Insert the value in sorted order.
data[insertionIndex + 1] = value;
}
}
2023-05-05 02:44:48 +03:00
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
2023-03-14 08:02:43 +03:00
{
2023-03-16 19:48:49 +03:00
foreach (var item in collection)
{
action.Invoke(item);
}
2023-03-14 08:02:43 +03:00
}
2023-03-16 19:48:49 +03:00
public static void Shuffle<T>(this IList<T> list)
2023-03-14 08:02:43 +03:00
{
2023-03-16 19:48:49 +03:00
Random random = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = random.Next(n + 1);
2023-07-20 17:44:06 +03:00
(list[k], list[n]) = (list[n], list[k]);
2023-03-16 19:48:49 +03:00
}
2023-03-14 08:02:43 +03:00
}
}
}