I have an algorithm written in Java that I would like to make more efficient. A part that I think could be made more efficient is finding the smallest of 3 numbers. Currentl
Use the Arrays.sort() method, the lowest value will be element0.
In terms of performance, this should not be expensive since the sort operation is already optimised. Also has the advantage of being concise.
private int min(int ... value) {
Arrays.sort(value);
return value[0];
}
Proof of concept
int[] intArr = {12, 5, 6, 9, 44, 28, 1, 4, 18, 2, 66, 13, 1, 33, 74, 12,
5, 6, 9, 44, 28, 1, 4, 18, 2, 66, 13};
// Sorting approach
long startTime = System.currentTimeMillis();
int minVal = min(intArr);
long endTime = System.currentTimeMillis();
System.out.println("Sorting: Min => " + minVal + " took => " + (endTime -
startTime));
System.out.println(startTime + " " + endTime);
System.out.println(" ");
// Scanning approach
minVal = 100;
startTime = System.currentTimeMillis();
for(int val : intArr) {
if (val < minVal)
minVal = val;
}
endTime = System.currentTimeMillis();
System.out.println("Iterating: Min => " + minVal + " took => " + (endTime
- startTime));
System.out.println(startTime + " " + endTime);