I've written two methods to find the smallest and largest int in an array, but they're nearly identical, so I feel like there should be some way to simplify this, perhaps as one method?
private int findMin(){
int min = arr[0];
for(int num : arr){
if(num<min) {
min = num;
}
}
return min;
}
private int findMax(){
int max = arr[0];
for(int num : arr){
if(num>max){
max = num;
}
}
return max;
}
I'm not sure how to approach this sort of issue, so I'd love to see your responses!
While this question on how to pass arithmetic operators to a method and this question on how to get both min and max value of Java 8 stream answer the literal programming problem, my question is on a more fundamental level about to how to approach the problem of methods doing similar things, and ways to compare arrays in general. The answers to this post have been significantly more helpful to me than the answers to those questions.