Minimum difference between any two elements in an array

Given an array, this function will find the minimum difference between any pair in given array and prints the minimum diference.

Example

INPUT :
arr[] = {5, 9, 23, 10}

OUTPUT :
Minimum difference is :1
The minimum difference between 10 and 9 is 1

Time Complexity : O()

Algorithm

1. Simply run two loops

2. In the outer loop select an element till end of the array. ie, i=0 to n-1, where n is the size

3. In the inner loop select an element from i+1 to n-1. ie, j=i+1 to n-1

4. Find the difference for each pair. If the new difference is less than the previous difference update the difference.

5. return the difference which is the minimum difference.

C++ Program

#include <bits/stdc++.h>

using namespace std;

int minDiff(int arr[], int n) //this function returns the minimum difference between any pair
{
	int diff = INT_MAX;			//initializing diff to maximum integer value
	for (int i = 0; i < n; ++i)	//finding difference for all pairs
	{
		for (int j = i+1; j < n; ++j)
		{
			if(abs(arr[i]-arr[j])<diff)
			{
				diff = abs(arr[i]-arr[j]);
			}
		}
	}
	return diff;  //minimum difference
}

int main()
{

	int arr[] = {5, 9, 23, 18, 10};	//initilaizing the array
	int n = sizeof(arr)/sizeof(arr[0]); //will give the size of the array
	int ans = minDiff(arr,n);
	cout<<"Minimum difference is "<<ans;
	return 0;
}
Try It

Time Complexity : O(nlogn)

Algorithm:

1. Sort the array in ascending order

    Till end of the array

a. compare all adjacent pair elements difference and keep track of the minimum difference

C++ Program

#include <bits/stdc++.h>
using namespace std;

int minDiff(int arr[], int n) //this function returns the minimum difference between any pair
{
	int diff = INT_MAX;  //initializing diff to maximum integer value
	sort(arr, arr+n);    //sorting the array which takes nlogn time
	for (int i = 0; i < n; i++) //finding difference between adjacent elements in the sorted array
	{
		if(arr[i+1]-arr[i]<diff)
		{
			diff = arr[i+1] - arr[i];
		}
	}

	return diff;  //minimum difference
}

int main()
{

	int arr[] = {5, 9, 23, 18, 10}; //initilaizing the array
	int n = sizeof(arr)/sizeof(arr[0]); //will give the size of the array
	int ans = minDiff(arr,n);
	cout<<"Minimum difference is "<<ans;
	return 0;
}
Try It

 


Next > < Prev
Scroll to Top