Q9. Write a method named minGap that accepts an integer array as a parameter and returns the minimum ‘gap’ between adjacent values in the array. The gap between two adjacent values in a array is defined as the second value minus the first value. For example, suppose a variable called array is an array of integers that stores the following sequence of values:
int[] array = {1, 3, 6, 7, 12};
The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1 (7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call of minGap(array) should return 1 because that is the smallest gap in the array. If you are passed an array with fewer than 2 elements, you should return 0.
import java.util.*;
import java.util.Scanner;
public class Q9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner (System.in);
System.out.println("Type a integer: ");
//決定數組大小
int numofarray = console.nextInt();
int []num = new int[numofarray];
for (int i=0;i<numofarray;i++) {
System.out.println("Type you #"+(i+1)+" number: ");
num[i]= console.nextInt();
}
int result = minGap(num);
System.out.println(result);
}
public static int minGap (int []array) {
int min =0;
if(array.length<=2) {
min=0;
}else if (array.length>2){
min =Math.min(array[1]-array[0],array[2]-array[1]);
for (int i=1;i<array.length;i++) {
if((array[i]-array[i-1])<min) {
min = array[i]-array[i-1];
}
}
}
return min;
}
}