So, I study the algorithms from this book that I acquired, and I have pseudo code to determine the distance between two closetst elements in an array of numbers
MinDistance(a[0...n-1]) Input: Array A of numbers Output: Minimum Distance between two of its elements dMin <- maximum integer for i=0 to n-1 do for j=0 to n-1 do if i!=j and | A[i] - A[j] | < dMin dMin = | A[i]-A[j] | return dMin
However, I would like to improve this algorithmic solution. Change what you already have, or rewrite everything together. Can anyone help? I wrote a function and class in Java to check pseudocode? It's right? And once again, how can I do it better in terms of efficiency.
//Scanner library allowing the user to input data import java.lang.Math.*; public class ArrayTester{ //algorithm for finding the distance between the two closest elements in an array of numbers public int MinDistance(int [] ar){ int [] a = ar; int aSize = a.length; int dMin = 0;//MaxInt for(int i=0; i< aSize; i++) { for(int j=i+1; j< aSize;j++) { dMin = Math.min(dMin, Math.abs( a[i]-a[j] ); } } return dMin; } //MAIN public static void main(String[] args){ ArrayTester at = new ArrayTester(); int [] someArray = {9,1,2,3,16}; System.out.println("NOT-OPTIMIZED METHOD"); System.out.println("Array length = "+ someArray.length); System.out.println("The distance between the two closest elements: " + at.MinDistance(someArray)); } //end MAIN } //END CLASS
SO I updated the function to minimize the call to Math.abs twice. What else can I improve? If I were to rewrite its varieties, change it for cycles in general or it would be just as theoretically faster.
public int MinDistance(int [] ar){ int [] a = ar; int aSize = a.length; int dMin = 0;
source share