第一种方法:

递归版本:

Error_Code binary_search(const Ordered_list &the_list, const Key &target, int bottom, int top,  int &position)

{

  Key data;

     if (bottom < top){

    int mid = bottom + (top - bottom)/2;   //注意点

    the_list.retrieve(mid, data);

    if (data < target)

      return binary_search(the_list, target, mid+1, top, position);

    else

      return binary_search(the_list, target, bottom, mid, position);

  } else if (bottom > top){

    return not_present;

  } else {

    position = bottom;

    the_list.retrieve(bottom, data);

    if (data == target) return success;

    else return not_present;

  }

}

非递归版本:

Error_Code binary_search(const Ordered_list &the_list, const Key &target,  int &position)

{

  Key data;

  int bottom = 0;

  int top = the_lsit.size() - 1;

     while (bottom < top){

    int mid = bottom + (top - bottom)/2;   //注意点

    the_list.retrieve(mid, data);

    if (data < target)

      bottom = mid + 1;

    else

      top = mid;

  } 

  if (bottom > top){

    return not_present;

  } else {

    position = bottom;

    the_list.retrieve(bottom, data);

    if (data == target) return success;

    else return not_present;

  }

}

第二种方法:

递归版本:

Error_Code binary_search(const Ordered_list &the_list, const Key &target, int bottom, int top,  int &position)

{

  Key data;

     if (bottom <=  top){

    int mid = bottom + (top - bottom)/2;   //注意点

    the_list.retrieve(mid, data);

    if (data == target){

      position = mid;

      return success;

    }else if (data < target)

      return binary_search(the_list, target, mid+1, top, position);

    else

      return binary_search(the_list, target, bottom, mid-1, position);

  } else {

    return not_present;

  }

}

非递归版本:

Error_Code binary_search(const Ordered_list &the_list, const Key &target,  int &position)

{

  Key data;

  int bottom = 0;

  int top = the_lsit.size() - 1;

     while (bottom <= top){

    position = bottom + (top - bottom)/2;   //注意点

    the_list.retrieve(mid, data);

    if (data == target){

      return success;

    } else if (data < target) {

      bottom = position+ 1;

    } else {

      top = position- 1;

    }

  } 

    return not_present;

}

posted on 2011-03-29 18:38  dylan_zb  阅读(201)  评论(0编辑  收藏  举报