This morning I passed by my secondary school campus. It has changed a lot with 2 brand new buildings. I started to learn programing in that school, where they taught me about palindrome and some very basic programming lessons. I don’t even remember what language was used back then. Probably basic.
Then I remember learning about OO and algorithms in university. One thing that still stick, well aside from some vague memory of OO principles, is recursive function. When I first heard about it, it’s a puzzle and very difficult to understand even when the source code is provided. But as I learned about it, I think it’s very clever.
It’s been 7-8 years since I wrote any code. I do shell scripts mostly which is just a bunch of procedures. Doesn’t require any algorithm. So I decided to write a recursive function which finds the smallest number from a list.
If I remember right, recursion involves 2 important parts. An ever reducing input data set and a finite condition. We feed the function a dataset, which returns a smaller dataset and in turn it’s fed to the same function. The result is returned to the previous level when a finite condition is met.
Here it is the source code. findMin is the recursive function. It compares the first number in a list with the rest of the numbers. When the rest of the numbers become just 1 number, a comparison result is returned. I certainly welcome any criticism or comments.
Yes I know I can do Collections.min() which probably is smarter and faster.
[code language=”java”]
import java.util.*;
public class Recurse {
public static void main(String args[]) {
// Create a list of random numbers
Random rand = new Random();
ArrayList<Integer> testData = new ArrayList<Integer>();
while ( testData.size() < 10 ) {
testData.add(rand.nextInt(99));
}
ArrayList<Integer> testDataCopy = new ArrayList<Integer>(testData);
// Display test data
System.out.println("Random numbers: " + testData.toString());
// Throw list into recursion
System.out.println("Smallest number: " + findMin(testData));
// Of course Java can do this for you
System.out.println("Result from Java Collections: " + Collections.min(testDataCopy));
}
public static int findMin(ArrayList<Integer> list) {
// If list is not 1 number, feed it back to same method
if (list.size() > 1) {
int tmpNum = list.get(0);
list.remove(0);
int tmpNum2 = findMin(list);
if (tmpNum < tmpNum2) {
return tmpNum;
} else {
return tmpNum2;
}
} else {
// Finite condition met, return number
return list.get(0);
}
}
}
[/code]