Skip to content

Commit

Permalink
Added Minimum Absolute Difference in Array Problem[C and C++] (jainam…
Browse files Browse the repository at this point in the history
  • Loading branch information
apoorvam25 authored and Mrunal committed Apr 8, 2020
1 parent 951da47 commit dab5d59
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*Given an integer array A of size N, find and return
the minimum absolute difference between any two elements in the array.
The absolute difference between two elements ai, and aj (where i != j ) is |ai - aj|*/

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>

int cmpfunc (const void * a, const void * b)
{
return (*(int*)a - *(int*)b);
}

int minAbsoluteDiff(int arr[], int n)
{
qsort(arr, n, sizeof(int), cmpfunc);
int mindiff = INT_MAX;
for(int i = 0; i < n - 1; i++)
{
if(abs(arr[i] - arr[i + 1]) < mindiff)
mindiff = abs(arr[i] - arr[i + 1]);
}
return mindiff;
}

int main()
{
int size, i;
scanf("%d", &size);
int input[size];
for(i = 0; i < size; i++)
scanf("%d", &input[i]);

printf("%d", minAbsoluteDiff(input,size));
return 0;
}

/* Input : 12
922 192 651 200 865 174 798 481 510 863 150 520
Output : 2
*/
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*Given an integer array A of size N,find and return
the minimum absolute difference between any two elements in the array.
The absolute difference between two elements ai, and aj (where i != j ) is |ai - aj|*/

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

int minAbsoluteDiff(int arr[], int n)
{
std::sort(arr, arr + n);
int mindiff = INT_MAX;
for(int i = 0; i < n - 1; i++)
{
if(abs(arr[i] - arr[i + 1] ) < mindiff)
mindiff = abs(arr[i] - arr[i + 1]);
}
return mindiff;
}

int main()
{
int size;
cin >> size;
int *input = new int[1 + size];

for(int i = 0; i < size; i++)
cin >> input[i];
cout << minAbsoluteDiff(input, size) << endl;
return 0;
}

/* Input : 5
2 9 0 4 5
Output : 1
*/

0 comments on commit dab5d59

Please sign in to comment.