QuickSort Script for PHP - sorting algorithm

earthdestroyer

New member
XNullUser
Joined
Dec 5, 2023
Messages
1
Reaction score
0
Points
1
Location
Moon
NullCash
9
Quicksort is one of the best storting algorithms.

Here is how you do it through PHP

PHP:
function quicksort($array) {
    // Base case: an array with 0 or 1 elements is already sorted
    $length = count($array);
    if ($length <= 1) {
        return $array;
    }

    // Choose a pivot element from the array
    $pivot_key = rand(0, $length - 1);
    $pivot = $array[$pivot_key];

    // Partition the array into two sub-arrays: elements less than the pivot and elements greater than the pivot
    $left = $right = [];
    foreach ($array as $key => $value) {
        if ($key == $pivot_key) {
            continue; // Skip the pivot element
        }
        $value < $pivot ? $left[] = $value : $right[] = $value;
    }

    // Recursively sort the sub-arrays and combine them with the pivot
    return array_merge(quicksort($left), [$pivot], quicksort($right));
}

Now, let's break down and describe the components of this function:

  1. Function Name: quicksort
    • This function is named quicksort and implements the quicksort algorithm for sorting an array.
  2. Parameters: $array
    • The function takes an array $array as input, which needs to be sorted.
  3. Base Case:
    • The base case checks if the length of the array is 0 or 1. If true, the array is considered sorted, and it is returned as is.
  4. Pivot Selection:
    • The function randomly selects a pivot element from the array. The choice of the pivot is crucial for the efficiency of the quicksort algorithm.
  5. Partitioning:
    • The array is partitioned into two sub-arrays: elements less than the pivot ($left) and elements greater than the pivot ($right).
    • A foreach loop is used to iterate through the array, and elements are placed in the appropriate sub-array based on their relationship to the pivot.
  6. Recursion:
    • The function recursively calls itself on the left and right sub-arrays.
    • The sorted sub-arrays are then combined with the pivot to form the final sorted array.
  7. Merge:
    • The array_merge function is used to combine the sorted left sub-array, pivot, and sorted right sub-array.
This function is more complex than the previous example because it involves not only recursion but also random pivot selection, array partitioning, and merging. The quicksort algorithm has a time complexity of O(n log n) on average, making it an efficient sorting algorithm for large datasets.
 
Top