
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Minimum Difference Between Any Two Elements in C++
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
Example
#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); }
Output
Minimum difference between two elements is: 4
Advertisements