#include<stdio.h>intmain(){int arr[]={1,2,3,4,5,6,7,8,9,10};int k =8;int i =0;int sz =sizeof(arr)/sizeof(arr[0]);//计算元素的个数for( i =0; i <= sz; i++){if(arr[i]== k){printf("找到了,下标是:%d\n", i);break;}}if(sz == i){printf("未找到\n");}return0;}
方法2:二分法
#include<stdio.h>intmain(){int arr[]={1,2,3,4,5,6,7,8,9,10};int k =8;int sz =sizeof(arr)/sizeof(arr[0]);//计算数据元素个数int left =0;//左下标int right = sz -1;//右下标int mid =0;//中下标while(left <= right){
mid =(right + left)/2;if(arr[mid]< k){
left = mid +1;}elseif(arr[mid]> k){
right = mid -1;}else{printf("找到了,下标是:%d\n", mid);break;}}if(left > right){printf("未找到\n");}return0;}
写一个函数,用二分法查找一个有序数组中的特定元素
#include<stdio.h>intbinary_search(int arr[],int x,int sz){int left =0;//左下标int right = sz -1;//右下标while(left <= right){int mid =(left + right)/2;//中间元素下标if(arr[mid]> x){
right = mid -1;}elseif(arr[mid]< x){
left = mid +1;}else{return mid;break;}}return-1;}intmain(){//利用二分查找一个有序数组中的某个数//如果找到了返回这个数的下标,找不到返回-1int arr[]={1,2,3,4,5,6,7,8,9,10};int k =7;int sz =sizeof(arr)/sizeof(arr[0]);//计算数组中元素的个数int ret =binary_search(arr,k,sz);//传递的是数组首个元素的地址if(ret ==1){printf("找不到指定的数字\n");}else{printf("找到了,下标是:%d\n", ret);}return0;}