You are on page 1of 2

Describing an algorithm

English:

"Find the largest number in the list"

Pseudocode (an “imperative” style of programming):

Write down the first number in the list, and call it 'max'
For each number in the list
if it's bigger than 'max'
replace the value of 'max' by the larger value
When we're all done, 'max' is the largest number we found

Python:

def findMax(list):
max = list[0]
for num in list:
if num > max:
max = num
return max

Java:

public static int findMax(int[] list)


{
int max = list[0];
for (int num : list)
{
if (num > max)
{
max = num;
}
}
return max;
}

C:  
int find_max(int * list, int size)  
{
int max = *list;
int * pos = list;
while (pos < list + size)
{
if (*pos > max)
{
max = *pos;
}
++pos;
}
return max;
}
Pseudocode (a “divide-and-conquer” strategy using recursion):

If the list has only one number in it, return that number.
Otherwise, return the maximum of a) the first number or b) the largest number in the rest of the list.

Python:

def find_max(list):
if len(list) == 1:
return list[0]
else:
return max(list[0], find_max(list[1:]))

Erlang:

findmax([A]) ->
A;
findmax([A | B]) ->
max(A, findmax(B)).

Clojure:

(defn findmax [list]


(if (= (count list) 1)
(first list)
(max (first list) (findmax (rest list)))))

Pseudocode (a “functional” style of programming):

Take a function that returns the max of two numbers, and reduce the list using that function.

Java:

public static int findMax(int[] list)


{
return Arrays.stream(list).reduce(list[0], (a, b) -> Math.max(a, b));
}

Python:

from functools import reduce

def find_max(list):
f = lambda a, b: a if (a > b) else b
return reduce(f, list)

You might also like