SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a method called minGap that accepts an integer array as a parameter and returns the minimum difference or gap between adjacent values in the array, where the gap is defined as the later value minus the earlier value. For

example, in the 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). So your method should return 1 if passed this array. The minimum gap could be a negative number if the list is not in sorted order. If you are passed an array with fewer than two elements, return 0.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of minGap method:

	public static int minGap(int[] a)
	{
		if(a.length < 2)
			return 0;
		
		int minGap = a[1] - a[0];
		
		for(int i = 1; i < a.length; i++)
		{
			if(a[i] - a[i - 1] < minGap)
			{
				minGap = a[i] - a[i - 1];
			}
		}
		
		return minGap;
	}
0 0

Discussions

Post the discussion to improve the above solution.