Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding out the minimum difference between elements in an array

Tags:

algorithm

I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array.

Consider that the array contains

4, 9, 1, 32, 13 

Here the difference is minimum between 4 and 1 and so answer is 3.

What should be the algorithm to approach this problem. Also, I don't know why but I feel that using trees, this problem can be solved relatively easier. Can that be done?

like image 330
OneMoreError Avatar asked Sep 02 '12 02:09

OneMoreError


People also ask

How do you find the smallest interval?

Subtract the smallest number from the largest number in the pair, this will generate the interval. Store in a variable the difference generated by every operation and update it only if the result is lower than the previous one, once it ends, the variable will store the smallest interval, which in this case is 2.

What is the minimum absolute difference?

The minimum absolute difference is the minimum value of absolute difference that can be achieved by picking up any two different elements among all possible integers from the given vector or array.


1 Answers

The minimum difference will be one of the differences from among the consecutive pairs in sorted order. Sort the array, and go through the pairs of adjacent numbers looking for the smallest difference:

int[] a = new int[] {4, 9, 1, 32, 13}; Arrays.sort(a); int minDiff = a[1]-a[0]; for (int i = 2 ; i != a.length ; i++) {     minDiff = Math.min(minDiff, a[i]-a[i-1]); } System.out.println(minDiff); 

This prints 3.

like image 149
Sergey Kalinichenko Avatar answered Sep 19 '22 21:09

Sergey Kalinichenko