ISEbd-12_Osyagina_A.A._Simple/LAB02/2/Program.cs
2024-05-01 12:26:51 +04:00

81 lines
2.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Alg;
class Program // БЫСТРАЯ СОРТИРОВКА (В лучшем случае O(n*log(n)), в худшем O(n^2))
{
static void Main(string[] args)
{
int[] myArray = randomGenerate(10, 1, 100); // Создаем массив из 10000 элементов со значениями от 1 до 1000000
Console.WriteLine("Исходный массив:");
printArray(myArray); // Выводим массив на экран
quickSort(myArray, 0, myArray.Length - 1); // Сортируем массив быстрой сортировкой
Console.WriteLine("Отсортированный массив:");
printArray(myArray); // Выводим отсортированный массив на экран
}
static int[] randomGenerate(int size, int minValue, int maxValue)
{
Random rnd = new Random();
int[] array = new int[size];
for (int i = 0; i < size; i++)
{
array[i] = rnd.Next(minValue, maxValue + 1); // Генерируем случайное число от minValue до maxValue
}
return array;
}
static void printArray(int[] array)
{
foreach (int num in array)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
static void quickSort(int[] array, int low, int high)
{
if (low < high)
{
int pivotIndex = partition(array, low, high);
// Рекурсивно сортируем элементы до и после опорного элемента
quickSort(array, low, pivotIndex - 1);
quickSort(array, pivotIndex + 1, high);
}
}
static int partition(int[] array, int low, int high)
{
int pivot = array[high];
int i = low - 1; // Индекс меньшего элемента
for (int j = low; j < high; j++)
{
// Если текущий элемент меньше или равен опорному
if (array[j] <= pivot)
{
i++;
// Обмен значениями
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Обмен значениями
int temp1 = array[i + 1];
array[i + 1] = array[high];
array[high] = temp1;
return i + 1;
}
}