Sort an array using the quicksort algorithm with average O(n log n) time complexity.
Code
Algorithmsfunction quicksort($a) {
if (count($a) <= 1) return $a;
$pivot = $a[0];
$rest = array_slice($a, 1);
$left = array_filter($rest, fn($x) => $x <= $pivot);
$right = array_filter($rest, fn($x) => $x > $pivot);
return array_merge(quicksort(array_values($left)), [$pivot], quicksort(array_values($right)));
}
quicksort($arr);Parameters
Array to sort
Server
More PHP Snippets
Bubble Sort
Sort an array using the bubble sort algorithm by repeatedly swapping adjacent elements.
Counting Sort
Sort an array of non-negative integers using counting sort for linear time performance.
Heap Sort
Sort an array using the heap sort algorithm with O(n log n) time complexity.
Insertion Sort
Sort an array using the insertion sort algorithm by building a sorted portion one element at a time.
Merge Sort
Sort an array using the merge sort algorithm with O(n log n) time complexity.
Selection Sort
Sort an array using the selection sort algorithm by repeatedly finding the minimum element.