求数组的距离
已知两个元素从小到大排雷的数组X[ ]与Y[ ],请写一个程序算出两个数组元素彼此之间差的绝对值中最小的一个,这叫做数组的距离
2010-04-05 20:56


2010-04-05 21:19
2010-04-06 11:15


2010-04-06 11:16
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int dist(int *x,int nx,int *y,int ny) //nx: 数组x的长度,ny:数组y的长度
{
int dist = abs(x[0]-y[0]);
int px = 0,py = 0;
while(px<nx && py<ny)
{
if(x[px]==y[py]) return 0;
if(x[px]<y[py])
{
if(dist > abs(x[px]-y[py]))
dist = abs(x[px]-y[py]);
px++;
}
if(x[px]>y[py])
{
if(dist > abs(x[px]-y[py]))
dist = abs(x[px]-y[py]);
py++;
}
}
return dist;
}
int main()
{
int x[] = {1,2,5,7,9};
int y[] = {3,11,12,18};
printf("%d\b",dist(x,5,y,4));//check
}
2010-04-06 11:23