Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Add QuickSort Algorithm Implementation #241

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions PHP/Sorting/QuickSort.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

function quickSort(array $array): array {
// Base case: arrays with 0 or 1 element are already "sorted"
if (count($array) < 2) {
return $array;
}

// Choose a pivot element
$pivot = $array[0];

// Partitioning step: elements smaller than the pivot, elements greater than the pivot
$left = array_filter(array_slice($array, 1), fn($x) => $x <= $pivot);
$right = array_filter(array_slice($array, 1), fn($x) => $x > $pivot);

// Recursively apply quicksort to left and right arrays, then merge
return array_merge(quickSort($left), [$pivot], quickSort($right));
}

// Example usage:
$array = [3, 6, 8, 10, 1, 2, 1];
$sortedArray = quickSort($array);
print_r($sortedArray);