diff --git a/Chapter4_QuickSort/Program.cs b/Chapter4_QuickSort/Program.cs index 65b9f80..9afbc75 100644 --- a/Chapter4_QuickSort/Program.cs +++ b/Chapter4_QuickSort/Program.cs @@ -17,3 +17,10 @@ int target = 42; int index = Task4_4.BinSearch(sortedArr, target, 0, sortedArr.Length - 1); Console.WriteLine($"4.4. Индекс числа {target} в массиве: {index}"); +// Пример использования QuickSort +List unsorted = new() { 5, 2, 9, 1, 7, 3 }; +Console.WriteLine("Быстрая сортировка"); +Console.WriteLine($"Неотсортированный список: {string.Join(", ", unsorted)}"); +var sorted = QuickSort.Sort(unsorted, Comparer.Default); +Console.WriteLine($"Отсортированный список: {string.Join(", ", sorted)}"); + diff --git a/Chapter4_QuickSort/QuickSort.cs b/Chapter4_QuickSort/QuickSort.cs new file mode 100644 index 0000000..ecac3be --- /dev/null +++ b/Chapter4_QuickSort/QuickSort.cs @@ -0,0 +1,37 @@ +static class QuickSort +{ + private static readonly Random _rnd = Random.Shared; + + public static List Sort(List source, Comparer comparer) + { + if (source.Count < 2) + return source; + + var referenceIndex = _rnd.Next(source.Count); + var reference = source[referenceIndex]; + var less = new List(); + var equal = new List(); + var more = new List(); + + 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; + } +} \ No newline at end of file