Catch! :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Pair
{
size_t first;
size_t second;
};
struct Pair minimum_difference( const int a[], size_t n )
{
struct Pair p = { 0 };
if ( 1 < n )
{
p.first = 0;
p.second = 1;
for ( size_t i = 0; i < n - 1; i++ )
{
for ( size_t j = i + 1; j < n; j++ )
{
// printf( "%d %d %llu\n", a[i], a[j],
// ( unsigned long long )abs( a[i] - a[j] ) );
if ( ( unsigned long long )abs( a[i] - a[j] ) <
( unsigned long long )abs( a[p.first] - a[p.second] ) )
{
p.first = i;
p.second = j;
}
}
}
}
return p;
}
int main(void)
{
const size_t N = 5;
const int UPPER_BOUND = 40 * N;
int a[N];
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ )
{
a[i] = rand() % ( 2 * UPPER_BOUND ) - UPPER_BOUND;
}
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
struct Pair p = minimum_difference( a, N );
printf( "(%d, %d)\n", a[p.first], a[p.second] );
return 0;
}
The program output might look loke
119 9 -193 21 -43
(9, 21)
This prpgram finds only the first pair with the minimum difference. If there are several pairs with the minimum difference when you have to allocate dynamically an array of pairs. Of course the function will be changed.
The other approach is to use a sort-copy algorithm by using an additional array. And then traverse this array calculating the difference.