0
<?php
function sortArray() {
    $inputArray = array(8, 2, 7, 4, 5);
    $outArray = array();
    for($x=1; $x<=100; $x++) {
        if (in_array($x, $inputArray)) {
            array_push($outArray, $x);
        }
    }
    return $outArray;
}


$sortArray = sortArray();
foreach ($sortArray as $value) {
    echo $value . "<br />";
}
?>

I have this code but there are two problems

  • What if my numbers in array are greater than 100?
  • Also, I'd like to see more than one method of sorting
j0k
  • 22,600
  • 28
  • 79
  • 90
Bashar Gh
  • 57
  • 1
  • 1
  • 5
  • 2
    How about using `count($inputArray)` instead of 100 and how about going to the [PHP docs](http://php.net/manual/en/array.sorting.php) to see more methods on sorting? – dbf Sep 13 '12 at 14:53
  • 4
    [Here a list of different Sorting algorithms](http://en.wikipedia.org/wiki/Sorting_algorithm#Summaries_of_popular_sorting_algorithms) – Martin Trenker Sep 13 '12 at 14:53
  • 1
    You could always use [`usort`](http://php.net/manual/en/function.usort.php) and write your own method. – Brad Christie Sep 13 '12 at 14:54
  • @martin sorting algorithms? damn you must be a fanatic :P – dbf Sep 13 '12 at 14:55
  • how i can use count($inputArray) and order this array? i don't want to use sort() or any built in function for sorting – Bashar Gh Sep 13 '12 at 14:56
  • 1
    @BasharGh - Like http://stackoverflow.com/users/425005/martin said checkout a sorting algorithm, I think bubblesort would be a good choice: http://en.wikipedia.org/wiki/Sorting_algorithm#Bubble_sort – Cyclonecode Sep 13 '12 at 14:58
  • 4
    *Why* do you not want to use built-in functions? Do you just want to reimplement a sorting algorithm for the sake of it? If so, what have you tried? – deceze Sep 13 '12 at 14:58
  • A decently usable, general sort will compare elements *with each other*, not with ints in an arbitrary range. If you tried this without limiting the ints, on my machine (running 64-bit PHP) it would take you millions of years to sort a dozen ints. – cHao Sep 13 '12 at 17:19
  • @deceze I know this is a very old question but a bug with usort and throwing exceptions is still not fixed. – DarkMukke Jun 12 '17 at 09:45
  • With modern PHP, use "array destructuring" to swap element positions without a temporary variable. https://stackoverflow.com/a/60012548/2943403 – mickmackusa Apr 08 '20 at 00:16

4 Answers4

31

Here is the way of sorting.

<?php

$array=array('2','4','8','5','1','7','6','9','10','3');

echo "Unsorted array is: ";
echo "<br />";
print_r($array);


for($j = 0; $j < count($array); $j ++) {
    for($i = 0; $i < count($array)-1; $i ++){

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}

echo "Sorted Array is: ";
echo "<br />";
print_r($array);

?>
Caramiriel
  • 7,029
  • 3
  • 30
  • 50
Tania
  • 334
  • 5
  • 3
  • 2
    Please explain what was the need for running two `for` loops? – Phantom007 Oct 20 '16 at 09:08
  • This sorting is for descending order of an array "; // Print array elements before sorting print_r($array); for ($i = 0; $i < $count; $i++) { for ($j = $i + 1; $j < $count; $j++) { if ($array[$i] > $array[$j]) { $temp = $array[$i]; $array[$i] = $array[$j]; $array[$j] = $temp; } } } echo "Sorted Array:" . "
    "; // Print array elements after sorting print_r($array); asc
    – sunil Nov 05 '16 at 07:04
  • 2
    @Phantom007 Because you need to compare each element in the array against each position in itself, if you do it only once the result would be `[4, 8, 5, 4, 2, 7, 6, 9, 10, 3, 1]` or something similar because you are only ever comparing the first one to it's neighbor and not to all of them, if it's just number coparing you could probably do something funky with min/max and only 1 loop but that would be very inefficient and not portable – DarkMukke Jun 12 '17 at 09:41
  • 1
    Code-only answers are low-value on Stackoverflow because they do a poor job of educating/empowering the OP and thousands of future researchers. Every answer should be explained -- even the simple/basic/self-explanatory/declarative ones. – Jitendra Pawar Jul 03 '20 at 13:37
7

Most of the other answers use two for loops to sort an array. At first the code seemed fairly straight and even I thought of the same. But then I wanted to investigate further. How efficient is this method? So using an array of 10,000 values, I used the two for loops method and got an execution time of 7.5 seconds

This is way too much. I'm sure PHP can't be this sloppy. So next I tested the in-built PHP rsort() function and got a time of 0.003 seconds.

Some research gave me the answer that PHP uses a quicksort algorithm to sort indexed arrays with a recursive function. I dug deeper and found a few examples of quicksearch for C++, Java etc. So, I replicated them in PHP, as follows:

/*
    The main function that implements QuickSort
    arr --> Array to be sorted,
    low  --> Starting index,
    high  --> Ending index
*/
function quickSort(&$arr, $low, $high)
{
    if ($low < $high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        $pi = partition($arr, $low, $high);
        // Separately sort elements before
        // partition and after partition
        quickSort($arr, $low, $pi - 1);
        quickSort($arr, $pi + 1, $high);
    }
    
    return $arr;
}

function partition (&$arr, $low = 0, $high)
{
    $pivot = $arr[$high];  // pivot
    $i = ($low - 1);  // Index of smaller element
 
    for ($j = $low; $j <= $high-1; $j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if ($arr[$j] <= $pivot)
        {
            $i++;    // increment index of smaller element
            swap($arr[$i], $arr[$j]);
        }
    }
    swap($arr[$i + 1], $arr[$high]);
    return ($i + 1);
}

function swap(&$a, &$b){
    $t = $a;
    $a = $b;
    $b = $t;
}

The time taken by this algorithm came out be: 0.023 seconds. Not as fast as rsort() but satisfactory.

miken32
  • 42,008
  • 16
  • 111
  • 154
Brajinder Singh
  • 159
  • 3
  • 8
1

This is my Quicksort algorithm in PHP:

<?php
$array = [1, 4, 3, 5, 9, 6, 1, 6, 4, 1, 1, 4, 5, 6, 6, 7, 2, 1, 4, 0];
$j = count($array);
$t = $j-1;
while($j>=0){
    for ($i=0; $i < $t; $i++) { 
        $aux = $array[$i]; 
        if($array[$i]>$array[$i+1]){
            $array[$i] = $array[$i+1];
            $array[$i+1] = $aux;
        }
    }
    $j--;
}
print_r($array);
Carlos Espinoza
  • 1,115
  • 11
  • 13
0

Sorting an array without using the built-in method but all the answers use the pre-defined method count.

I am just trying to refactor it. Please find the below answer.

$array = [50,12, 30, 10, 9, 14];
$count = 0;
foreach($array as $elem){
    $count++;
}
for ($i = 0; $i < $count; $i++) {
    for ($j = 0; $j < $count - 1; $j++) {
        if ($array[$j] > $array[$j + 1]) { 
            $temp = $array[$j];
            $array[$j] = $array[$j + 1]; 
            $array[$j +1] = $temp; 
        }
    }
}
print_r($array); 
Soubhagya Kumar Barik
  • 1,979
  • 20
  • 26
  • 1
    Again with the 2 `for` loops. What do you think this added that wasn't already present for years? – miken32 May 26 '22 at 14:24