Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple logic problem: Finding largest and smallest number among 3 numbers

I am creating a pseudocode in determining the smallest and largest number among 3 numbers:

My code is as follows:

If (x >= y)  
   largest = x
   Smallest = y
Else 
    largest = y
    Smallest =x

If (z >= largest)
    Largest = z
If (z <= smallest)
    Smallest = z

Do you think this is correct? or are there better ways to solve this?

like image 562
newbie Avatar asked Dec 04 '22 22:12

newbie


1 Answers

Let's say you've got arbitrary numbers x, y, z.

Pseudocode:

largest = x
smallest = x

if (y > largest)  then largest = y
if (z > largest)  then largest = z

if (y < smallest) then smallest = y
if (z < smallest) then smallest = z

This is one way to solve your problem if you're using only variables, assignment, if-else and comparison.


If you have arrays and a sort operation defined over it, you can use this:

array = [x, y, z]
arrays.sort()
largest  = array[2]
smallest = array[0]

If you have a max and min function that takes an array of numbers as an argument, you can use this:

array = [x, y, z]
largest  = max(array)
smallest = min(array)

If you also have positional assignment using sets, you can use this:

array = [x, y, z]
(largest, smallest) = (max(array), min(array))

If you have a data structure that will sort it's contents when inserting elements, you can use this:

array.insert([x, y, z])
smallest = array[0]
largest = array[2]
like image 122
darioo Avatar answered Dec 07 '22 12:12

darioo