Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
