# c语言小白学习历程第六篇

2020-11-09 12:53:19

2020年11月1日

# 学习产出：

c语言二分法实现数据查找

``````#include<stdio.h>
/******************
函数实现二分法
*******************/
int binary_research(int arr[],int length,int element)
{

int left = 0;
int right = 0;
right = length - 1;
while (left <= right) {

int mid = (left + right) / 2;
if (arr[mid] > element) {

right = mid - 1;
} else if {

(arr[mid] < element)
left = mid + 1;
} else {

return mid;
}
}
return -1;
}

int main()
{

int numStr[] = {

4, 7, 8, 45, 64, 123, 564, 586, 614, 688, 999};
int left = 0;
int right = 0;
int mid = 0;
int checkNum = 0;
int numLen = 0;

printf("可供查找的字符串是:\nnumStr[] = {4, 7, 8, 45, 64, 123, 564, 586, 614, 688, 999}\n");
scanf("%d", &checkNum);

numLen = sizeof(numStr) / sizeof(int);

//mid = binary_research(numStr, numLen, checkNum);

right = numLen - 1;
mid = (left + right) / 2;

// 普通方法实现二分发查找
while (left <= right) {

if (numStr[mid] > checkNum) {

right = mid -1;
} else if (numStr[mid] < checkNum) {

left = mid + 1;
} else {

break;
}
mid = (left + right) / 2;
}

printf("mid = %d\n", mid);

return 0;
}
``````

https://my.oschina.net/u/4267017/blog/4709446