创建函数利用二分法
#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>#include<math.h>#include<string.h>int judge(int arr[], int k,int length){ int left = 1; int right = length; while (left<=right) { int mid = (right + left) / 2; if (arr[mid - 1] < k) { left = mid + 1; } else if (arr[mid - 1 > k]) { right = mid - 1; } else if (arr[mid - 1] == k) return mid - 1; } return -1;}int main(){ char arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int length = strlen(arr); int x = 0; printf("请输入1-10内您想查找的数字\n"); scanf("%d", &x); int ret = judge(arr, x,length); if (ret == -1) { printf("找不到这个数字\n"); } else { printf("找到了,下标是%d\n", x -1); } return 0;}