Page 1 of 1

logical statement and sorting

Posted: Wed May 13, 2009 7:42 pm
by drelicious_23
hi.. im just a newbie in php.. i would just like to ask about the assign our professor left for us..
the problem is this: there will be 3 input numbers, the string for these three numbers are A,B,C.. then next step, the "if-lse" statement.. it will first process if it is greater than or less than the other number.. then it will sort out from highest to lowest and vice versa..
example:
$a = 11;
$b = 10;
$c = 31;
how can i do it? thank you in advance! :)

Re: logical statement and sorting

Posted: Wed May 13, 2009 8:25 pm
by ldougherty
OK so let me understand this..

You are going to have a form with 3 input fields that are for inputting integers which will be assigned to $a, $b, and $c

Then based upon the input you need to be able to sort them?

There are much better ways to do this rather than if else such as

Code: Select all

 
 
$numbers = array($a,$b,$c);  ## Store the integers in an array
$lowtohigh = sort($numbers);   ## Sort the Array from low to high
$hightolow = arsort($numbers); ## Sort the Array from high to low
 
foreach ($lowtohigh as &$value) {
    echo "$value<br>";
}
 
echo "<br><br>";
 
foreach ($hightolow as &$value) {
    echo "$value<br>";
}
 
 
If you definitely have to use an if else just think through the logic to determine which is the largest number

if $a > $b and $a > $c you know $a will be the largest.
if $a > $b but $a < $c then you know $b will be the largest
if $a < $b then compare $b to $c to see which is the largest

Once you have the largest you can use else statements to display the other two values.

hope that helps.

Re: logical statement and sorting

Posted: Thu May 14, 2009 4:30 am
by Yossarian
Bubble sort might be the term that your prof wants you to become familiar with.


EDIT
While simple, this algorithm is highly inefficient and is rarely used except in education.
Or then again maybe not ... http://en.wikipedia.org/wiki/Sorting_algorithm