PHP Quick Sort: Algorithm & Implementation
Quick sort is a commonly used and efficient sorting algorithm that works by dividing an array into two smaller subarrays, sorting each subarray, and then combining them to complete the sorting of the entire array.
Here is a method for implementing quicksort in PHP.
function quickSort($arr) {
if (count($arr) <= 1) {
return $arr;
}
$pivot = $arr[0];
$left = $right = array();
for ($i = 1; $i < count($arr); $i++) {
if ($arr[$i] < $pivot) {
$left[] = $arr[$i];
} else {
$right[] = $arr[$i];
}
}
return array_merge(quickSort($left), array($pivot), quickSort($right));
}
$arr = array(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
$sortedArr = quickSort($arr);
print_r($sortedArr);
The code above implements a simple quicksort algorithm, where the first element of the array is chosen as the pivot in each recursive call. Elements smaller than the pivot are placed in the left array, while those larger are placed in the right array. Finally, the left and right arrays are merged with the pivot element to obtain the sorted array.