From my Java post : https://homanhduc.wordpress.com/2012/02/13/first-java-assignmentpart-ii/

Median is the middle number that divides the array number into 2 halves: the left half and the right half

Finding the middle number of 3 number is of a small scale of the problem.

It is the X number such that : smallest of the three < x < biggest of the three.

My approach would be:

**1.Find the biggest of the three that can be accomplished through using bigger procedure(function):**

def bigger(a,b):
#always return the larger of the two
if a > b:
return a
#b > a
return b

Biggest function

def biggest(a,b,c):
return bigger(bigger(a,b),c)

**2. Save the biggest value into a variable.**

3. Since we don’t know which one of the three variable is the biggest(we only know the value of the biggest), we makes some test:

If a is the largest:

return the bigger of (b,c)

Else if b is the largest:

return the bigger of (a,c)

Else return the bigger of (a,b)

So this is the code :

def median(a,b,c):
#get the biggest number
bg = biggest(a,b,c)
#if a is the biggest
if a == bg:
return bigger(b,c)
else:
#b is the biggest
if b == bg:
return bigger(a,c)
else:
#c is the biggest
return bigger(a,b)

Full code:

def bigger(a,b):
if a > b:
return a
else:
return b
def biggest(a,b,c):
return bigger(a,bigger(b,c))
def median(a,b,c):
#get the biggest number
bg = biggest(a,b,c)
#if a is the biggest
if a == bg:
return bigger(b,c)
else:
#b is the biggest
if b == bg:
return bigger(a,c)
else:
#c is the biggest
return bigger(a,b)
#test case
print median(3,6,7)
print median(6,7,5)
print median(1,0,7)
print median(1,2,3)
print median(12,1,9)

Sample run :

6

6

1

2

9

### Like this:

Like Loading...

*Related*