题目内容:
写一个二分查找函数
功能:在一个升序数组中查找指定的数值,找到了就返回下标,找不到就返回 - 1.
int bin_search(int arr[], int left, int right, int key)
arr 是查找的数组
left 数组的左下标
right 数组的右下标
key 要查找的数字
我在这个项目里写了2种函数,一种是暴力遍历查找,另一个则是二分查找,可以通过选择注释进行切换。代码如下,已有注释。
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> int chazhaooo(int arr[], int key,int a) //二分查找 { int left = 0; int right = a; int b = 0; while (left <= right) { b = (left + right) / 2; if (arr[b] == key) { return b; } else if (arr[b] < key) { left = b + 1; } else { right = b - 1; } } return -1; arr[(left + right) / 2]; } int chazhao(int arr[], int key, int a)//暴力遍历查找 { int b = 0; for (int b = 0;b < a;b++) { if (arr[b] == key) { return b; } } return -1; } int main() { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; int key = 0; int jieguo = 0; int a = sizeof(arr) / sizeof(int)-1; scanf("%d",&key); //printf("%d",key); //jieguo=chazhao(arr, key, a);//暴力遍历查找 jieguo = chazhaooo(arr, key, a);//二分查找 printf("%d", jieguo); return 0; }