二分查找法

#include<stdio.h>

int BinarySearch(const int a[],const int t,int lengh) ///暂时没错的版本,注意middle最好不要直接赋值,因为那样如果找不到,会引起死循环
{
  printf("%d",sizeof(a));///放到这里输出为4
  int start = 0, end = lengh - 1;
  while(start <= end)
  {
    printf("start = %d and end = %d \n",start,end);
    int middle = start + (end - start)/2;
    if(a[middle] == t)
        return middle;
    else if(a[middle] < t)
        start = middle + 1;
    else
        end = middle - 1;
  }
  printf("The end");
}

int BinarySearchRecuision(const int a[], const int t, int start, int end)
{
    if(start > end)
        return -1;
    int middle = (start + end)/2;
    if(a[middle] == t)
        return middle;
    else if (t > a[middle])
        return BinarySearchRecuision(a,t,middle+1,end);
    else
        return BinarySearchRecuision(a,t,start,middle-1);
}///这估计就是传说中的分治法吧~

void main()
{
    int a[] = {1,2,3,5}; 
    int lengh = sizeof(a)/sizeof(a[0]);
    printf("%d",sizeof(a)); ///放到这里输出为16
    BinarySearch(a,5,lengh);
}

 

posted on 2014-05-17 12:09  berkeleysong  阅读(135)  评论(0编辑  收藏  举报

导航