Created
March 17, 2018 18:50
-
-
Save vadimkorr/5963aa6aa2d3f5d83b9ba96ec70a2beb to your computer and use it in GitHub Desktop.
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment