Home > Mobile >  Sorting an array of numbers with for-loop
Sorting an array of numbers with for-loop

Time:10-14

I have a task of sorting an array of numbers in both ascending and descending order. The challenge is, I can't use the built-in sort function, but loop through the array with for-loops instead.

I am a total newbie when it comes to PHP and this task straight off baffles me. Here is the code I'm supposed to work with:

<?php
  $arr = $_GET['arr'];
  $table = explode(',', $arr);
  
  $count = count($table);
  
  // What I tried to work with, didn't get to work:
  for ($i = 0; $i < $count; $i  ) {
      for ($j = $i   1; $j < $count; $j  ) {
          if ($table[$i] > $table[$j]) {
              $temp = $table[$i];
              $table[$i] = $table[$j];
              $table[$j] = $temp;
              $asc = implode("," $temp);
          }
      }
  }
  
  echo "Ascending: $asc";
  echo "Descending: $desc";
?>

Any clue why this doesn't run? At some point, I got the first (largest) number in the array with the echo, but don't really know what broke that either.

CodePudding user response:

Move the line

$asc = implode(",", $temp);

from its current location below the outer for loop and maybe add the line

$desc = implode(",", array_reverse($temp));

to get the descending sort order.

CodePudding user response:

Many ways to make it. One solution you will find in the code below. you will certainly notice that the sorting depends only on one operator. Therefore, you can build a function out of it by specifying the sorting as a parameter. function(array $array, string $sort) {}

DESC

    $arr= array(112,21,130,140,2,42);
    for($i=0; $i<count($arr)-1; $i  )
    {
        for($j=0; $j<count($arr)-1; $j  )
        {
            if($arr[$j] < $arr[$j 1]){
                $temp= $arr[$j 1];
                $arr[$j 1]= $arr[$j];
                $arr[$j]= $temp;
            }
        }

    }
    print_r($arr);

Output:

Array
(
    [0] => 140
    [1] => 130
    [2] => 112
    [3] => 42
    [4] => 21
    [5] => 2
)

ASC

    $arr= array(112,21,130,140,2,42);
    for($i=0; $i<count($arr)-1; $i  )
    {
        for($j=0; $j<count($arr)-1; $j  )
        {
            if($arr[$j] > $arr[$j 1]){
                $temp= $arr[$j 1];
                $arr[$j 1]= $arr[$j];
                $arr[$j]= $temp;
            }
        }

    }
    print_r($arr);

Output

Array
(
    [0] => 2
    [1] => 21
    [2] => 42
    [3] => 112
    [4] => 130
    [5] => 140
)
  •  Tags:  
  • php
  • Related