#define N 15
main()
{int a[N],i,j,n,tem,flag=1,number,top,bott,mid,loca,sign=1;
char c;
printf(“enter the array of line is:”);
scanf(“%d”,&n);
printf(“\n”);
printf(“enter the number of array:”);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n”);
for(j=0;j<=n-2;j++)
for(i=0;i<n-j-1;i++)
if(a[i]<a[i+1]){tem=a[i];a[i]=a[i+1];a[i+1]=tem;}
printf(“output the array:”);
for(i=0;i<n;i++)
printf(“%3d”,a[i]);
printf(“\n”);
flag=1;
printf(“enter the another number:”);
scanf(“%d”,&number);
while(flag)
{top=0;bott=n-1;loca=0;
if(number>a[0]||number<a[n-1])loca=-1;
while((sign==1)&&(top>=bott))
{mid=(bott+top)/2;
if(number==a[mid]){loca=mid;
printf(“find %d, its position is %d\n”,number,loca+1);
sign=0;}
else if(number<a[mid])top=mid+1;
else bott=mid-1;}
if(sign==1||loca==-1)
printf(“%d is not found \n”,number);
printf(“continue or not(Y/N)?”);
continue;
scanf(“%c”,&c);
if(c==’N'||c==’n')flag=0;
}
}
是输入一个数组,按大小i拍了,在输入个数 在数组中找到它,有的话输出这个数和它在数组的位置,如果没有,输出无。大侠帮小弟个忙呀,在此表示感谢!
>> 本文固定链接: http://www.vcgood.com/archives/2683
源程序有比较多的问题,重新写了一些,
输出的数组的位置现在是原始位置(而不是内部排序后的位
置),如果需要排序后的位置,把 pos【mid】改为mid即可
#define N 15
main()
{
int a[N],pos[N],
int i,j,n,tem,number,top,bott,mid;
char c;
printf(“enter the array of line is: < 15 \n”);
scanf(“%d”,&n);
printf(“\n”);
printf(“enter each item of array (total %d):\n”,n );
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
pos[i] = i;
}
printf(“\n”);
for(j=0;j<=n-2;j++)
{
for(i=0;i<n-j-1;i++)
if(a[i]<a[i+1])
{
tem=a[i];
a[i]=a[i+1];
a[i+1]=tem;
tem = pos[i];
pos[i] = pos[i+1];
pos[i+1] = tem;
}
}
printf(“output the array:”);
for(i=0;i<n;i++)
printf(“%3d”,a[i]); // 数组是降序排列
printf(“\n”);
for(i=0;i<n;i++)
printf(“%3d”,pos[i]); // 数组是降序排列
printf(“\n”);
while (1)
{
printf(“enter the another number: 0 to exit \n”);
scanf(“%d”,&number);
if (number==0)
break;
bott=0; // 数组小头
top=n-1; // 数组大头
while(top>=bott)
{
mid=(bott+top)/2;
if(number==a[mid])
{
printf(“find %d, its position is
%d\n”,number,pos[mid]);
break;
}
else
if(number<a[mid])
bott=mid+1;
else
top=mid-1;
}
if (top<bott)
printf(“%d is not found \n”,number);
}
return 0 ;
}