Question
Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].
Examples:
Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 and 2 is 1.
Solution
dmin ← ∞
dmin← |A[i] - A[j]|
return dmin
// C program to Find the minimum// distance between two numbers
#include <stdio.h>
{
int i, j;
int min_dist =30000;
for (i = 0; i < n; i++)
y == arr[i] && x == arr[j]) && min_dist > abs(i-j))
{
min_dist = abs(i-j);
}
}
}
return min_dist;
}
int main()
{
int arr[100];
int n,i;
int x;
int y;
printf("Enter the no elements required in array\n ");
scanf("%d",&n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the elements whose distance u want\n");
scanf("%d %d",&x,&y);
printf("Minimum distance between %d and %d is %d\n",x, y,minDist(arr, n, x, y));
return 0;
Enter the no elements required in array
1
2
3
4
5
Enter the elements whose distance u want
2
5
Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].
Examples:
Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1 and 2 is 1.
Solution
0 comments:
Post a Comment