Horje
How to Sort an Array containing 1 to n values in PHP ?

In this article, we will see how to sort an array that contains 1 to n values in PHP. There are various approaches through which we can sort an array with custom values. Below is an example for a better understanding of the problem statement.

Example:

Input: arr = [3, 1, 4, 5, 2, 8, 9, 5]
Output: Sorted Array is: [1, 2, 3, 4, 5, 8, 9]

Input: arr = [3, 1, 4, 5, 2, 0, 10]
Output: Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

There are two methods to sort an array that contains 1 to n values:

Using PHP sort() Function

We will use the built-in sort() function to sort the input array into ascending to descending order. It sorts the actual array and hence changes are reflected in the original array itself. 

Syntax

sort(array &$array, int $sort_flags = SORT_REGULAR): bool

Example: This example uses the built-in sort() function to sort the input array into the correct order.

PHP
<?php
function sortArray($arr)
{
    sort($arr);
    return $arr;
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = sortArray($arr1);
$result2 = sortArray($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>

Output
Sorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

Using a Custom Sorting Algorithm (Bubble Sort)

We will use the Bubble sort algorithm to manually sort the array without relying on any built-in approach to sort the array. Here, the loops are used to iterate over the array elements and sort them in the correct order.

Syntax

function bubbleSort(&$arr) {
$n = count($arr);
for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {

// Swap $arr[$j] and $arr[$j+1]
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
}
}

Example: This example uses the custom sorting algorithm (Bubble Sort) to sort the input array elements.

PHP
<?php
function customSortArray($arr)
{
    $n = count($arr);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = 0; $j < $n - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = customSortArray($arr1);
$result2 = customSortArray($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>

Output
Sorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

Using a Custom Sorting Algorithm (Quicksort)

We will use the Quicksort algorithm to manually sort the array without relying on any built-in approach to sort the array. Quicksort is a divide-and-conquer algorithm that is efficient for large datasets.

PHP
<?php
function quickSort(&$arr) {
    if(count($arr) < 2) {
        return $arr;
    }
    $left = $right = array();
    reset($arr);
    $pivot_key = key($arr);
    $pivot = array_shift($arr);
    foreach($arr as $k => $v) {
        if($v < $pivot)
            $left[$k] = $v;
        else
            $right[$k] = $v;
    }
    return array_merge(quickSort($left), array($pivot_key => $pivot), quickSort($right));
}
$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
$result1 = quickSort($arr1);
$result2 = quickSort($arr2);
echo "Sorted Array is: [" . implode(", ", $result1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $result2) . "]\n";
?>

Output
Sorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

Using a Custom Sorting Algorithm (Insertion Sort)

Insertion Sort is a simple and efficient comparison-based sorting algorithm. It builds the final sorted array one item at a time, with each iteration removing an element from the input data and inserting it into the correct position in the already sorted part of the array.

Example: This example uses the custom sorting algorithm (Insertion Sort) to sort the input array elements.

PHP
<?php
function insertionSort(&$arr) {
    $n = count($arr);
    for ($i = 1; $i < $n; $i++) {
        $key = $arr[$i];
        $j = $i - 1;

        // Move elements of $arr[0..$i-1], that are greater than $key, to one position ahead of their current position
        while ($j >= 0 && $arr[$j] > $key) {
            $arr[$j + 1] = $arr[$j];
            $j--;
        }
        $arr[$j + 1] = $key;
    }
}

$arr1 = [3, 1, 4, 5, 2, 8, 6, 10, 7];
$arr2 = [3, 1, 4, 5, 2, 0, 10];
insertionSort($arr1);
insertionSort($arr2);
echo "Sorted Array is: [" . implode(", ", $arr1) . "]\n";
echo "Sorted Array is: [" . implode(", ", $arr2) . "]\n";
?>

Output
Sorted Array is: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Sorted Array is: [0, 1, 2, 3, 4, 5, 10]

Using Merge Sort

Merge Sort is a divide-and-conquer algorithm that recursively divides the array into halves, sorts each half, and then merges the sorted halves to produce a sorted array. Merge Sort is efficient for large datasets and has a time complexity of O(n log n).

Example:

PHP
<?php
function mergeSort($arr) {
    if (count($arr) <= 1) {
        return $arr;
    }
    
    $mid = floor(count($arr) / 2);
    $left = array_slice($arr, 0, $mid);
    $right = array_slice($arr, $mid);
    
    $left = mergeSort($left);
    $right = mergeSort($right);
    
    return merge($left, $right);
}

function merge($left, $right) {
    $result = [];
    $i = 0;
    $j = 0;
    
    while ($i < count($left) && $j < count($right)) {
        if ($left[$i] < $right[$j]) {
            $result[] = $left[$i];
            $i++;
        } else {
            $result[] = $right[$j];
            $j++;
        }
    }
    
    while ($i < count($left)) {
        $result[] = $left[$i];
        $i++;
    }
    
    while ($j < count($right)) {
        $result[] = $right[$j];
        $j++;
    }
    
    return $result;
}

$arr = [3, 1, 4, 5, 2, 8, 9, 5];
$sortedArray = mergeSort($arr);

echo "Sorted Array is: ";
print_r($sortedArray);
?>

Output
Sorted Array is: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 5
    [6] => 8
    [7] => 9
)



Reffered: https://www.geeksforgeeks.org


PHP

Related
PHP move_uploaded_file() Function PHP move_uploaded_file() Function
Difference Between Core PHP and CakePHP Difference Between Core PHP and CakePHP
PHP String Programs PHP String Programs
PHP Array Programs PHP Array Programs
PHP hebrev() Function PHP hebrev() Function

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14