Saturday, January 5, 2013

Implement a Java method that finds two neighbouring numbers in an array with the smallest distance to each other.



Implement a Java function that finds two neighbouring numbers in an array with the smallest distance to each other. The function should return the index of the first number.

In the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2). The function should return the index 3 (of number 1).

class LangFund3{
    static void smallestDistance(int [] array){
   
        int smallest = Math.abs(array[0]-array[1]);
        int index = 0;
        for(int i=1; i<array.length-1; i++){
            int value = Math.abs(array[i]-array[i+1]);
            if(value< smallest){
            smallest= value;
            index = i;
            }
               
        }
        System.out.println(smallest);
        System.out.println(index);   
           
    }
    public static void main(String [] args){
        int []arr= new int[]{4,8,6,1,2,9,4};
        smallestDistance(arr);
    }
}

2 comments: