Open In App

Implementation of Quick Sort in PHP

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Quick Sort is a widely used sorting algorithm known for its efficiency and speed. It follows the divide-and-conquer paradigm, sorting an array by selecting a pivot element and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot. In this article, we will explore the implementation of Quick Sort in PHP.

Quick Sort is a sorting algorithm based on the Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array.

Choice of Pivot Element

There are many different choices for picking pivots.

  • Always pick the first element as a pivot.
  • Always pick the last element as a pivot (implemented below)
  • Pick a random element as a pivot.
  • Pick the middle as the pivot.

Basic Quick Sort Implementation

The basic Quick Sort algorithm involves selecting a pivot, partitioning the array, and recursively sorting the sub-arrays.

PHP




<?php
  
function quickSort($array) {
    $length = count($array);
  
    if ($length <= 1) {
        return $array;
    } else {
        $pivot = $array[0];
        $left = $right = array();
  
        for ($i = 1; $i < $length; $i++) {
            if ($array[$i] < $pivot) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
  
        return array_merge(
            quickSort($left), 
            array($pivot), 
            quickSort($right)
        );
    }
}
  
// Driver code
$array = array(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
$sortedArray = quickSort($array);
  
echo "Original Array: " . implode(", ", $array) . "\n";
echo "Sorted Array: " . implode(", ", $sortedArray);
  
?>


Output

Original Array: 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5
Sorted Array: 1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads