Quick Index
Purpose


In this example we'll demonstrate how to write an algorithm for another common problem -- finding a matching element.

We'll use a function so we start to get a feel for functions.

Writing Algorithm


find(elements, compareFct)
Problem Statement:
Write an algorithm to find the first matching element in a collection named "elements". Use "compareFct" to determine if we have a match. Return the index of the match, or "-1" if no match.

Given:
  • Variable 'elements' that holds a collection of objects
  • Variable 'compareFct', when evaluated like this "compareFct(anElem)", returns true if "anElem" is a "match"
Sample 1:

Sample 2:
Writing Algorithm in Human Language
Write the algorithm in human language (English).


Human Language:
find(elements, compareFct) {
	Let 'i' equal to zero
	Let 'len' equal to length of 'elements'
	While 'i' is less than 'len'
		Let 'nextElement' equal to the element in 'elements' at index 'i'
		If (compareFct(nextElement))
			Return i;
		Let 'i' equal to 'i' plus 1
Return -1
}
Writing Algorithm in Pseudocode
Write the algorithm in pseudocode.


Pseudocode:
function find(elements, compareFct)  {
	let len = elements.length
	let i = 0
	while (i < len) {
		let nextElem = elements[i]
		if (compareFct(nextElem))
			return i
		i = i + 1
	}
	return -1
}

//Try It
let nums = [2, 10, 20, 30, 31, 40, 41]

//First num >= 20;
let matchFct = (nextNum) => nextNum >= 20;
let matchIndex = find(nums, matchFct);
println("Match (>=20): " + nums[matchIndex]);

//First odd num
matchFct = (nextNum) => nextNum % 2 != 0
matchIndex = find(nums, matchFct);
println("Match (first odd): " + nums[matchIndex]);