69,371
社区成员
发帖
与我相关
我的任务
分享
int n; /*全局变量*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void shu(int str[],int m) /*让数组从小到大排列*/
{
int i,j,t;
n = m;
for(j=0;j <m-1;j++)
for(i=0;i <m-1-j;i++)
if(str[i]>str[i+1])
{
t=str[i];
str[i]=str[i+1];
str[i+1]=t;
}
}
int wei(int str[],int x) /*用半折查找法找到X的下标*/
{
int z,zx,zd,s,w;
zx=0;
s=1;
zd=n-1;
w=0;
z=0;
if((x <str[0])||(x>str[n-1]))
printf("此数不在数组中!\n");
else
while(s==1&&z>=0)
{
z=(zx+zd)/2;
if(x==str[z])
{
w=z;
s=0;
}
else if(x <str[z])
zd=z-1;
else if(x>str[z])
zx=z+1;
}
if(s==1)
printf("此数不在数组中!\n");
else
return(w);
}
void main()
{
int str[20];
int x,w,i;
for(i=0;i <3;i=i+4)
{
printf("请输入数组的4个值(?,?,?,?):\n");
scanf("%d%d%d%d",&str[i],&str[i+1],&str[i+2],&str[i+3]); //去掉,
}
fflush(stdin);
printf("请输入查找的数值:\n");
scanf("%d",&x);
shu(str,4);
w=wei(str,x);
printf("查找的数是:%d;\n此数的下标是:%d",str[w],w);
getch();
}
int n; /*全局变量*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
void shu(int str[],int m) /*让数组从小到大排列*/
{
int i,j,t;
n = m;
for(j=0;j <m-1;j++)
for(i=0;i <m-1-j;i++)
if(str[i]>str[i+1])
{
t=str[i];
str[i]=str[i+1];
str[i+1]=t;
}
}
int wei(int str[],int x) /*用半折查找法找到X的下标*/
{
int z,zx,zd,s,w;
zx=0;
s=1;
zd=n-1;
w=0;
z=0;
if((x <str[0])||(x>str[n-1]))
printf("此数不在数组中!\n");
else
while(s==1&&z>=0)
{
z=(zx+zd)/2;
if(x==str[z])
{
w=z;
s=0;
}
else if(x <str[z])
zd=z-1;
else if(x>str[z])
zx=z+1;
}
if(s==1)
printf("此数不在数组中!\n");
else
return(w);
}
void main()
{
int str[20];
int x,w,i;
for(i=0;i <3;i=i+4)
{
printf("请输入数组的4个值(?,?,?,?):\n");
scanf("%d,%d,%d,%d",&str[i],&str[i+1],&str[i+2],&str[i+3]);
fflush(stdin);
}
printf("请输入查找的数值:\n");
scanf("%d",&x);
shu(str,4);
w=wei(str,x);
printf("查找的数是:%d;\n此数的下标是:%d",str[w],w);
getch();
}
int n = 20; /*全局变量,定义数组长度*/
#include <stdio.h>
void shu(int str[]) /*让数组从小到大排列*/
{
int i,j,t;
//n=strlen(str); 去掉
for(j=0;j <n-1;j++)
for(i=0;i <n-1-j;i++)
if(str[i]>str[i+1])
{
t=str[i];
str[i]=str[i+1];
str[i+1]=t;
}
}
int wei(int str[],int x) /*用半折查找法找到X的下标*/
{
int z,zx,zd,s,w;
zx=0;
s=1;
zd=n-1;
w=0;
z=0;
if((x <str[0])||(x>str[n-1]))
printf("此数不在数组中!\n");
else
while(s==1&&z>=0)
{
z=(zx+zd)/2;
if(x==str[z])
{
w=z;
s=0;
}
else if(x <str[z])
zd=z-1;
else if(x>str[z])
zx=z+1;
}
if(s==1)
printf("此数不在数组中!\n");
else
return(w);
}
void main()
{
int wei(int str[],int x);
void shu(int str[]);
int str[n]; //数组长度用n
int x,w,i;
for(i=0;i < n;i++)
{
printf("请输入数组的4个值(?,?,?,?):\n");
scanf("%d",&str[i]);//这样比较好
}
printf("请输入查找的数值:\n");
scanf("%d",&x);
shu(str);
w=wei(str,x);
printf("查找的数是:%d;\n此数的下标是:%d",str[w],w);
getch();
}
void shu(int str[]) /*让数组从小到大排列*/
{
int i,j,t;
n=strlen(str); //strlen是操作字符串的函数,你这样操作系统会崩掉
for(j=0;j <n-1;j++)
for(i=0;i <n-1-j;i++)
if(str[i]>str[i+1])
{
t=str[i];
str[i]=str[i+1];
str[i+1]=t;
}
}