To find minimum distance of two sorted lists where distance is the absolute difference of pair of elements

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

int minDist(int a[], int m, int b[], int n){

int i = 0,
j = 0,
min = INT_MAX,
cur;

while(i < m && j < n) {

cur = abs(a[i] - b[j]);

min = min < cur ? min : cur;

if(a[i] < b[j])
i++;
else
j++;
}

return min;
}

int main() {

int a[] = {2, 3, 5, 11, 18, 19, 20};
int b[]= {15, 24, 27, 29};


printf("%d\n", minDist(a, sizeof(a)/sizeof(int), b, sizeof(b)/sizeof(int)));

return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s