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

Updated on: 19-Dec-2019

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements