## Shortest distance between 2 Integers

#include <iostream> #include <climits> using namespace std; int dist(int a[],int n, int x, int y) { int a1=-1,a2=-1, min_distance = INT_MAX; for(int i=0;i<n;i++) { if(a[i]==x) { a1 = i; int distance = a1-a2; if(a2>=0 && distance<min_distance) { min_distance = distance; } } else if(a[i]==y) { a2 = i; int distance = a2-a1; if(a1>=0 && distance<min_distance) { min_distance = distance; } } } return min_distance; } int main() { int a[] = {6,5,5,5,1,2,4,4,6,6,3,4,3,4,1,2,4}; int size= sizeof(a)/sizeof(a[0]); cout<<dist(a,size,1,6); return 0; }

Advertisements

No comments yet.

Advertisements

## Leave a Reply