Manual Quicksort

This commit is contained in:
Ilya Rogozhin
2026-06-10 10:38:18 +02:00
parent 459d048596
commit a752b27bc9
2 changed files with 124 additions and 14 deletions
+54 -14
View File
@@ -22,7 +22,7 @@ class TestFHRSort extends Command
$array = []; $array = [];
for ($i = 0; $i < $count; $i++) { for ($i = 0; $i < $count; $i++) {
$array[] = rand(0, $count); $array[] = rand(-200000, $count);
} }
$memoryBefore = memory_get_usage(); $memoryBefore = memory_get_usage();
@@ -31,9 +31,9 @@ class TestFHRSort extends Command
$this->comment('Before sorting:'); $this->comment('Before sorting:');
$this->comment('Memory usage: ' . round($memoryBefore / 1024 / 1024, 2) . ' MB'); $this->comment('Memory usage: ' . round($memoryBefore / 1024 / 1024, 2) . ' MB');
$this->info('Sorting the array using PHP\'s built-in sort()...'); $this->info('Sorting the array using manual Quicksort implementation...');
sort($array); $this->quickSort($array, 0, count($array) - 1);
$timeAfter = microtime(true); $timeAfter = microtime(true);
$memoryAfter = memory_get_usage(); $memoryAfter = memory_get_usage();
@@ -51,20 +51,60 @@ class TestFHRSort extends Command
$this->line(implode(', ', array_slice($array, -12))); $this->line(implode(', ', array_slice($array, -12)));
$this->info('Sort test finished.'); $this->info('Sort test finished.');
}
$this->line(' /**
* Реализация алгоритма Быстрой сортировки (Quicksort) "на месте".
* @param array $arr Сортируемый массив (передается по ссылке).
* @param int $low Индекс начала подмассива.
* @param int $high Индекс конца подмассива.
*/
private function quickSort(array &$arr, int $low, int $high): void
{
if ($low < $high) {
// pi - это индекс опорного элемента, arr[pi] теперь на своем месте.
$pi = $this->partition($arr, $low, $high);
Для сортировки большого массива в PHP, особенно когда // Рекурсивно сортируем элементы до и после опорного.
важны и скорость, и потребление памяти, встроенная $this->quickSort($arr, $low, $pi - 1);
функция `sort()` является лучшим выбором. $this->quickSort($arr, $pi + 1, $high);
Она реализована на C и использует алгоритм Quicksort, который }
является одним из самых быстрых для среднего случая (O(n log n)). }
`sort()` выполняет сортировку "на месте" (in-place), что означает,
что она не требует выделения дополнительной памяти, пропорциональной
размеру массива, что делает ее очень эффективной по памяти.
Для большинства практических задач в PHP это оптимальное решение. /**
* Вспомогательная функция для quickSort.
* Разделяет массив на две части относительно опорного элемента.
* @param array $arr
* @param int $low
* @param int $high
* @return int Индекс, на котором теперь стоит опорный элемент.
*/
private function partition(array &$arr, int $low, int $high): int
{
// В качестве опорного элемента (pivot) берем последний элемент.
$pivot = $arr[$high];
'); // i - индекс меньшего элемента.
$i = ($low - 1);
for ($j = $low; $j <= $high - 1; $j++) {
// Если текущий элемент меньше или равен опорному.
if ($arr[$j] <= $pivot) {
$i++; // Увеличиваем индекс меньшего элемента.
// Меняем местами arr[i] и arr[j].
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
// Ставим опорный элемент на его правильную позицию,
// меняя местами arr[i+1] и arr[high] (опорный элемент).
$temp = $arr[$i + 1];
$arr[$i + 1] = $arr[$high];
$arr[$high] = $temp;
return ($i + 1);
} }
} }
@@ -0,0 +1,70 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('app:test-fhr-sort-v0')]
#[Description('Написать сортировку для массива числовых данных от 200 тысяч элементов (v0)')]
class TestFHRSort_v0 extends Command
{
/**
* Execute the console command.
*/
public function handle()
{
$this->info('Starting the sort test...');
$count = 200000;
$this->comment("Generating an array of $count random numbers...");
$array = [];
for ($i = 0; $i < $count; $i++) {
$array[] = rand(0, $count);
}
$memoryBefore = memory_get_usage();
$timeBefore = microtime(true);
$this->comment('Before sorting:');
$this->comment('Memory usage: ' . round($memoryBefore / 1024 / 1024, 2) . ' MB');
$this->info('Sorting the array using PHP\'s built-in sort()...');
sort($array);
$timeAfter = microtime(true);
$memoryAfter = memory_get_usage();
$this->comment('After sorting:');
$this->comment('Memory usage: ' . round($memoryAfter / 1024 / 1024, 2) . ' MB');
$this->comment('Memory increase: ' . round(($memoryAfter - $memoryBefore) / 1024, 2) . ' KB');
$this->comment('Time taken: ' . round($timeAfter - $timeBefore, 4) . ' seconds');
$this->line('');
$this->info('First 12 elements:');
$this->line(implode(', ', array_slice($array, 0, 12)));
$this->info('Last 12 elements:');
$this->line(implode(', ', array_slice($array, -12)));
$this->info('Sort test finished.');
$this->line('
Для сортировки большого массива в PHP, особенно когда
важны и скорость, и потребление памяти, встроенная
функция `sort()` является лучшим выбором.
Она реализована на C и использует алгоритм Quicksort, который
является одним из самых быстрых для среднего случая (O(n log n)).
`sort()` выполняет сортировку "на месте" (in-place), что означает,
что она не требует выделения дополнительной памяти, пропорциональной
размеру массива, что делает ее очень эффективной по памяти.
Для большинства практических задач в PHP это оптимальное решение.
');
}
}