Quick Index
Overview


Helper algorithms (or "helper methods") just means any other algorithms we call from the one we are working on.

We previously wrote an algorithm for "Making Tomato Sandwiches". One possibility for that algorithm was to call another algorithm named "Make Toast". That way the caller is simplified.

Pseudocode Example


Let's say we are writing the algorithm (p-code) for the method "findClosestToEnd".

The method header is shown to the right.

Remember, we are coding in a MyArray object -- so it is part of our context (environment).
findClosestToEnd(compareFct) {
	//ALGORITHM HERE
}
First we'll just scribble out a quick "rough" algo in any human language for the purpose is just helping us get going with pseudocode.

Note for the two searches we use the arg "compareFct" that is provided to the algorithm.
findClosestToEnd(compareFct) {
	firstIndex = get index of first (left) end of array
	lastIndex = get index of last (right) end of array
	firstMatchingIndex	= search for first matching elem (index)
	lastMatchingIndex = search for last matching elem (index)
	leftDistance = distance from firstIndex to the firstMatchingIndex
	rightDistance = distance from lastMatchingIndex to the lastIndex
}
Algos are all about iteration. Here is our second, improved, scribble of our "human" algorithm.

We can see that four of the steps require only simple math.

But the other two steps (searches) are going to require some serious work.
findClosestToEnd(compareFct) {
	firstIndex = 0
	lastIndex = this.length - 1
	firstMatchingIndex	= search for first matching elem (index)
	lastMatchingIndex = search for last matching elem (index)
	leftDistance = firstMatchingIndex - firstIndex
	rightDistance = lastIndex - lastMatchingIndex
}
But wait! What is our context/scope? What other objects and algorithms (methods) do we have available?

We know have "MyArray" (the object we are coding in -- i.e. "this").

The question is, does it provide a method(s) that will help us with the searches?
	firstMatchingIndex = search for first matching element (index) using compareFct
	lastMatchingIndex = search for last matching element (index) using compareFct
Browsing a MyArray listing, we see an algorithm (method) named findIndex

If we read about that algorithm, we learn it does exactly what we need for our search to find the first matching index.

We should also look for something similar for finding the last matching index.
MyArray algorithms (methods) menu:
If we do not find a algorithm (method) that will do the job we may still consider adding a helper algorithm to make our current algorithm simpler.