一、代码
#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
#define MAXSIZE 20
typedef int Status
;
Status
binarySearch(int arr
[],int arrLenght
,int wantSearchElement
);
int main(int argc
, char *argv
[]) {
int data
[MAXSIZE
],size
,i
,wantSearch
,result
;
printf("请输入初始化数组大小(1-%d):",MAXSIZE
);
scanf("%d",&size
);
printf("请输入数组元素(空格隔开):");
for(i
=1;i
<=size
;i
++)
{
if(scanf("%d",&data
[i
])==0)
{
printf("输入错误\n");
fflush(stdin);
return ERROR
;
}
}
printf("请输入你要查找的内容:");
if(scanf("%d",&wantSearch
)==0)
{
printf("输入错误\n");
fflush(stdin);
return ERROR
;
}
if((result
=binarySearch(data
,size
,wantSearch
))==ERROR
)
{
printf("你要查找的元素不在数组中\n");
return ERROR
;
}
printf("元素在数组中%d位置\n",result
);
return 0;
}
Status
binarySearch(int arr
[],int arrLenght
,int wantSearchElement
)
{
int low
=1,hight
=arrLenght
,mid
;
while(hight
>=low
)
{
mid
=(low
+hight
)/2;
if(arr
[mid
]>wantSearchElement
)
{
hight
=mid
-1;
}
else if(arr
[mid
]<wantSearchElement
)
{
low
=mid
+1;
}else
{
return mid
;
}
}
return ERROR
;
}
二、代码中重要的函数或语句
(一)、核心代码
Status
binarySearch(int arr
[],int arrLenght
,int wantSearchElement
)
{
int low
=1,hight
=arrLenght
,mid
;
while(hight
>=low
)
{
mid
=(low
+hight
)/2;
if(arr
[mid
]>wantSearchElement
)
{
hight
=mid
-1;
}
else if(arr
[mid
]<wantSearchElement
)
{
low
=mid
+1;
}else
{
return mid
;
}
}
return ERROR
;
}
三、运行截图
转载请注明原文地址:https://blackberry.8miu.com/read-2041.html