logical statement and sorting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
drelicious_23
Forum Newbie
Posts: 1
Joined: Wed May 13, 2009 7:35 pm

logical statement and sorting

Post 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! :)
ldougherty
Forum Contributor
Posts: 103
Joined: Sun May 03, 2009 11:39 am

Re: logical statement and sorting

Post 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.
Yossarian
Forum Contributor
Posts: 101
Joined: Fri Jun 30, 2006 4:43 am

Re: logical statement and sorting

Post 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
Post Reply