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
#include
using namespace std;
int getMinimumDifference(int a[], int n) {
   sort(a, a+n);
   int min_diff = INT_MAX;
   for (int i=0; i

Output

Minimum difference between two elements is: 4
Updated on: 2019-12-19T10:12:02+05:30

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements