Write a method named minGap hat accepts an integer array as
Write a method named minGap (hat 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 l because that is the smallest gap in the array. If you are passed an array with fewer than 2 elements, you should return o. You should submit: Java code Screenshot of the output of your program.
Solution
Hi, Plesae find my code.
Please let me know in case of any issue.
public class MinGap {
public static int minGap(int[] arr){
// base case
if(arr == null || arr.length < 2)
return 0;
int mingap = arr[1] - arr[0]; // initializing min gap
for(int i=2; i<arr.length; i++){
int currGap = arr[i] - arr[i-1];
if(mingap > currGap)
mingap = currGap;
}
return mingap;
}
public static void main(String[] args) {
int arr[] = {1, 3, 6, 7, 12};
int minGap = minGap(arr);
System.out.println(\"Min Gap: \"+minGap);
}
}
/*
Sample Output:
Min Gap: 1
*/

