I have a Minimum Difference algorithm, and I wanted to expand on it by printing the actual elements that were subtracted. I'm just wanting to know if this is the best way to do it.
public static int findMinimumDifference(int[] arr) {
int minuend = 0; //initialize them here
int subtrahend = 0;
Arrays.sort(arr); //sort the array first
int difference = 0;
if (arr.length == 1) {
difference = arr[0];
}
if (arr.length > 1) {
difference = Math.abs(arr[0] - arr[1]); //This will give only positive integers for difference - e.g. 6 - 7 = -1 = 1
for (int i = 0; i <= arr.length; i++) {
if (i + 1 < arr.length) { //as long as we're not at the end yet
int temp = Math.abs(arr[i] - arr[i + 1]); // temp variable is assigned to difference of consecutive elements i and i + 1
if (temp < difference) // if temp is the new minimum difference, assign difference to temp
difference = temp;
if(arr[i + 1] - arr[i] == difference) {
minuend = arr[i + 1]; //Here's where I assign them
subtrahend = arr[i];
}
}
}
}
if(arr.length == 1) { //If there's only one element it will
//display arr[0] - 0 = arr[0]
//e.g. 12 - 0 = 12
System.out.print(arr[0] + " - " + minuend + " = ");
}
else { //otherwise, show the subtraction
System.out.print(minuend + " - " + subtrahend + " = ");
}
return difference;
}
}
This is the output for two arrays as an example:
int[] array1 = {5, 16, 3, 32, 6}; int[] array2 = {13, 22, 37, 40, 11, 99, 100, 222, 1000, 101, 9999, 10000}; The minimum differences in the arrays are: 6 - 5 = 1 10000 - 9999 = 1
NOTE: I understand that second array actually has another subset (99, 100) that will equal 1. I just haven't figured out how to display both sets yet. I will work on that later.