Minimum Absolute Difference in an Array

Minimum Absolute Difference in an Array

Given an array of integers,find and print the minimum absolute difference between any two elements in the array. for example given the array A=[-2,2,4] we can create 3 pairs of numbers [-2,2],[-2,4] and [2,4].The difference for these pairs are 4,6 and 2 .The minimum absolute difference is 2.

Sample input :
3 //number of elements in array
3 -7 0
Sample output:
3
Explanation:
|3 - -7| = 10
|3-0| = 3
|-7-0|=7
minimum difference is 3.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
int main()
{
    int a[10],i,j,diff,n,k; //number of elements in array
    int arr[10],count=0,m,min; //array contains all possible diff in an array
    printf("Enter the number of elements : ");
    scanf("%d",&n);
    printf("enter the array elements :");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<n-1;i++)
    {
        k=i+1;
        for(j=k;j<n;j++)
        {
            diff=a[i]-a[j];
            arr[count]=abs(diff); //difference stored in second array
            count++;
        }
    }
    //find the smallest number in the second array 
    min=arr[0];
    for(m=1;m<count;m++)
    {
        if(arr[m]<min)
        {
            min=arr[m];
        }
    }
    printf("minimum absolute difference = %d",min);
    return 0;
}
OUTPUT:



0 comments