/** * Utilities for finding interesting facts about arrays of integers. * * @author Samuel A. Rebelsky * @author Carla Caffeinated * @author Carl Caffeinated * @version 1.0 of October 1999 */ public class DifferenceComputer { /** * Determine the greatest difference between any pair of values * in the an array of integers. * Pre: The array is nonempty. * Pre: The greatest difference is less than the maximum integer. * Post: Returns the largest |values[i]-values[j]|. */ public int greatestDifference(int[] values) { int estimate = 0; int difference; // For each value, values[i], in the collection for (int i = 0; i < values.length; ++i) { // For each value, values[j], in the collection for (int j = 0; j < values.length; ++j) { // Determine the difference between the two values difference = Math.abs(values[i]-values[j]) ; // If it's bigger than the biggest difference so far then if (difference > estimate) { // Update our estimate of the biggest difference estimate = difference; } } // for j } // for i return estimate; } // greatestDifference(int[] values) /** * Determine the greatest difference between any pair of values * in the an array of integers. * Pre: The array is nonempty. * Pre: The greatest difference is less than the maximum integer. * Post: Returns the largest |values[i]-values[j]|. */ public int leastDifference(int[] values) { int estimate = Integer.MAX_VALUE; int difference; // For each value, values[i], in the collection for (int i = 0; i < values.length; ++i) { // For each value, values[j], in the collection for (int j = 0; j < values.length; ++j) { // If the two values are not the same if (values[i] != values[j]) { // Determine the difference between the two values difference = Math.abs(values[i]-values[j]) ; // If it's smaller than the least difference so far then if (difference < estimate) { // Update our estimate of the least difference estimate = difference; } } // if the two values are different } // for j } // for i return estimate; } // leastDifference(int[] values) } // class DifferenceComputer