- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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 element 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

- Related Questions & Answers
- Program to find minimum difference between two elements from two lists in Python
- Find the minimum difference between Shifted tables of two numbers in Python
- Difference between find Element and find Elements in Selenium
- Find the minimum distance between two numbers in C++
- Program to find the maximum difference between the index of any two different numbers in C++
- C++ code to find minimum difference between concerts durations
- Find the Symmetric difference between two arrays - JavaScript
- Python program to find difference between two timestamps
- Find difference between sums of two diagonals in C++.
- Find the compatibility difference between two arrays in C++
- C++ Program to find minimum difference between strongest and weakest
- C++ program to find minimum difference between the sums of two subsets from first n natural numbers
- Find the difference between two datetime values with MySQL?
- How to find set difference between two Numpy arrays?
- Python Pandas – Find the Difference between two Dataframes

Advertisements