[Глава 4] Быстрая сортировка

This commit is contained in:
Пытков Роман
2025-07-26 22:44:47 +03:00
parent 83d5f60fe9
commit 455ef1ba54
2 changed files with 44 additions and 0 deletions

View File

@@ -17,3 +17,10 @@ int target = 42;
int index = Task4_4.BinSearch(sortedArr, target, 0, sortedArr.Length - 1); int index = Task4_4.BinSearch(sortedArr, target, 0, sortedArr.Length - 1);
Console.WriteLine($"4.4. Индекс числа {target} в массиве: {index}"); Console.WriteLine($"4.4. Индекс числа {target} в массиве: {index}");
// Пример использования QuickSort
List<int> unsorted = new() { 5, 2, 9, 1, 7, 3 };
Console.WriteLine("Быстрая сортировка");
Console.WriteLine($"Неотсортированный список: {string.Join(", ", unsorted)}");
var sorted = QuickSort.Sort(unsorted, Comparer<int>.Default);
Console.WriteLine($"Отсортированный список: {string.Join(", ", sorted)}");

View File

@@ -0,0 +1,37 @@
static class QuickSort
{
private static readonly Random _rnd = Random.Shared;
public static List<T> Sort<T>(List<T> source, Comparer<T> comparer)
{
if (source.Count < 2)
return source;
var referenceIndex = _rnd.Next(source.Count);
var reference = source[referenceIndex];
var less = new List<T>();
var equal = new List<T>();
var more = new List<T>();
for (var i = 0; i < source.Count; i++)
{
var value = source[i];
if (comparer.Compare(value, reference) < 0)
less.Add(value);
else if (comparer.Compare(value, reference) > 0)
more.Add(value);
else if (comparer.Compare(value, reference) == 0)
equal.Add(value);
}
less = Sort(less, comparer);
more = Sort(more, comparer);
var index = 0;
foreach (var item in less)
source[index++] = item;
foreach (var item in equal)
source[index++] = item;
foreach (var item in more)
source[index++] = item;
return source;
}
}