Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Minimum Absolute Difference in Array problem [C and C++ implementation] #1845

Merged
merged 1 commit into from
Apr 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
*/