//这里假设把数组a,//定义第一位和最后一个的下标

 编程     |      2020-03-18 20:24

#include<stdio.h>
int find(int *arr,int low, int hight,int key)
{
    int mid=(hight+low)/2 ;
    if(hight<lowState of Qatar return -1;//管理不在数组内之数 ,此处参考网络工夫,感到很抢眼
    if(arr[mid]!=key)
    {
    if(arr[mid]>key) return find(arr,low,mid-1,key);
    else  return find(arr,mid+1,hight,key);
    }
    else return mid;
}
int main()
{
  int  arr[]={1,2,3,4,5,6,7,9,16};
  printf("数组地方:%dn", find(arr, 0,  8, 3));
  printf("数组地点:%dn", find(arr, 0,  8, 7));
  printf("数组地方:%dn", find(arr, 0,  8, 19));
竞博下载 ,  return 0;
}

#include <stdio.h> int binSearch(int, int, int卡塔尔; main(卡塔尔国 { int i, n = 10, x = 7; //这里借使把数组a[]定义为a[n],是漏洞比较多的,不能够定义变长数组。 int a[10]; printf("Please enter your num:/n"State of Qatar; //从标准输入给数组赋值的并世无双方法:用for循环 for(i=0;i<n;i++卡塔尔 { scanf("%d",&a[i]); } printf("The %d can be found in the arr, it is %dth of the arr/n", x, binSearch(x,a,n)); } /*先是种方式,测度都在循环内*/ int binSearch(int x, int a[], int n卡塔尔(قطر‎{ int low, high, mid; low = 0; high = n-1; //注意,这里不可不用<=, 用<不得法,一贯重回-1 while(low <= high卡塔尔(قطر‎ { mid = (low + high卡塔尔国 / 2; if(x < a[mid]) high = mid - 1; else if(x > a[mid]) low = mid + 1; else return mid; } return -1; } /*在循环内运转一遍測试的办法*/ /*int binSearch(int x, int a[], int n) { int low, high, mid; low = 0; high = n-1; mid = (low + high) / 2; while((low <= high)&&(a[mid]!=x)) { if(x < a[mid]) high = mid -1; else low = mid + 1; mid = (low + high) / 2; } if(a[mid] == x) return mid; else return -1; } */

二分查找  有序数组

 

int mid = (low + high)/2;

岁月复杂度   log2n

if (a [mid] == key) {


                Console.WriteLine ("find key,index", mid);

                 return mid;                                  //返回值 mid

} else if (a[mid] > key) {

                  high = mid - 1;

} else if (a[mid] < key) {

                  low = mid + 1;

}

int[] arr = {1,2,3,4,5,6,7,8 };

int low = 0, hight = arr.Length - 1;          //定义第一个人和尾声三个的下标

int key = 7;

while (low <= hight) {

                   int mid = (low + hight) / 2;

                   if (arr[mid] == key) {

                                 Console.WriteLine ("find,index="+mid);         //找到,下标为 :

                                 break;

                   }else if (arr[mid]>key) {

                                 hight = mid - 1;

                   }else if (arr[mid]<key) {

                                 low = mid + 1;

                   }

}

if (low > hight){

     Console.WriteLine ("404");

}