Minimum difference between two elements in array | Letuscode
Given an array, how do we find the minimum difference between any two elements in that array?
For example consider the array
Read full article from Minimum difference between two elements in array | Letuscode
Given an array, how do we find the minimum difference between any two elements in that array?
For example consider the array
[56, 18, 89, 24, 10]
, the minimum difference is 6 (between 18, and 24)./* brute force algorithm */ int min_diff1(vector<int>& arr) | |
{ | |
int min_diff = INT_MAX; | |
int i,j; | |
for( i = 0; i < arr.size()-1; i++ ) | |
{ | |
for( j = i+1; j < arr.size(); j++ ) | |
{ | |
min_diff = min(min_diff, abs(arr[i]-arr[j])); | |
} | |
} | |
return min_diff; | |
} | |
int min_diff(vector<int>& arr) | |
{ | |
sort( arr.begin(), arr.end() ); | |
int min_diff = INT_MAX; | |
for( i = 0; i < n-1; i++ ) | |
{ | |
min_diff = min(min_diff, abs(arr[i]-arr[i+1])); | |
} | |
return min_diff; | |
} |