- Related Questions & Answers
- Program to find minimum difference between two elements from two lists in Python
- Find the minimum distance between two numbers in C++
- Find the minimum difference between Shifted tables of two numbers in Python
- Program to find the maximum difference between the index of any two different numbers in C++
- Find difference between sums of two diagonals in C++.
- Find the compatibility difference between two arrays in C++
- Program to find the minimum edit distance between two strings in C++
- Find the shortest distance between any pair of two different good nodes in C++
- C++ Program to Find Minimum Value of any Algebraic Expression
- Find the Symmetric difference between two arrays - JavaScript
- C# difference in milliseconds between two DateTime
- Find the difference between two datetime values with MySQL?
- How to find set difference between two Numpy arrays?
- Difference between two given time periods in C++
- Find the difference between two timestamps in days with MySQL

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of n elements called A. We have to find the minimum difference between any two elements in that array. Suppose the A = [30, 5, 20, 9], then the result will be 4. this is the minimum distance of elements 5 and 9.

To solve this problem, we have to follow these steps −

Sort the array in non-decreasing order

Initialize the difference as infinite

Compare all adjacent pairs in the sorted array and keep track of the minimum one

#include<iostream> #include<algorithm> using namespace std; int getMinimumDifference(int a[], int n) { sort(a, a+n); int min_diff = INT_MAX; for (int i=0; i<n-1; i++) if (a[i+1] - a[i] < min_diff) min_diff = a[i+1] - a[i]; return min_diff; } int main() { int arr[] = {30, 5, 20, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum difference between two elements is: " << getMinimumDifference(arr, n); }

Minimum difference between two elements is: 4

Advertisements