Given an array of n integers, find and print the minimum absolute difference between any two elements in the array (where i!=j, 2<=n<=10^9)
// Given an array of n integers, find and print the minimum absolute difference
// between any two elements in the array (where i!=j, 2<=n<=10^9)
function findMinDiff(arr) {
let n = arr.length;
// Sort array in non-decreasing order
arr.sort(function(a, b) {
return a - b;
});
// Initialize difference as infinite
let diff = Infinity;
// Find the min diff by comparing adjacent
// pairs in sorted array
for (let i=0; i<n-1; i++) {
let localDiff = arr[i+1] - arr[i];
if (localDiff < diff)
diff = localDiff;
}
// Return min diff
return diff;
}
let arr = [1, 5, 3, 19, 18, 25];
console.log(findMinDiff(arr)); // 1