Jump to content

[SOLVED] Finding the largest number in a list


Schlo_50

Recommended Posts

Hello guys!

 

I have a short list of about 50 (could be more, could be less) numbers stored in a text file. I would to be able to find the largest number and print it out to the browser.

 

My code can't find the true largest number, and uses the BubbleSort function.

 

print "The largest number in the file is:<br /><br />";

function BubbleSort($sort_array,$column = 0,$reverse = 1)
{
  $lunghezza=count($sort_array);
  for ($i = 0; $i < $lunghezza ; $i++){
    for ($j = $i + 1; $j < $lunghezza ; $j++){
      if($reverse){
        if ($sort_array[$i][$column] < $sort_array[$j][$column]){
          $tmp = $sort_array[$i];
          $sort_array[$i] = $sort_array[$j];
          $sort_array[$j] = $tmp;
        }
      }else{
        if ($sort_array[$i][$column] > $sort_array[$j][$column]){
          $tmp = $sort_array[$i];
          $sort_array[$i] = $sort_array[$j];
          $sort_array[$j] = $tmp;
        }
      }
    }
  }
  return $sort_array;          
}


$bfile = file("numbers.DAT");

foreach($bfile as $key => $value)
{
$tmp = explode('|', $value);
$vals[] = $tmp[1];
}
rsort($vals);
$vals = BubbleSort($vals);

print $vals[1].'<br />';

 

Input:

none|1
none|2
none|13
none|4
none|5
none|6
none|101000000
none|950
none|93
none|8
none|11
none|121010101
none|3
none|14
none|16

 

Output:

950

 

Thanks in advance!

You can try using typecasting. Like so:

 

$input = file("numbers.dat");

$numbers = array();
$data = array();

foreach($input as $line){
$tmp_exp = explode("|", $line);
$data[] = (int) $tmp_exp[1]; //Notice the (int)
}
$largestNumber = max($data);
echo "Largest number is ".$largestNumber;

 

Notice the (int), that converts the string to an integer. This could be the problem.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.