template <class T>
int dichotomy(T arr, int len, int com)
{
  int start = 0;
  int end = len;
  int index = len / 2;
  while (start <= end)
  {
    if (arr[index] > com)
    {
      end = index - 1;
      index = index / 2;
    }
    else if (arr[index] < com)
    {
      start = index + 1;
      index = start + (end - start) / 2;
    }
    else if (arr[index] == com)
    {
      return index;
    }
  }
  return -1;
}

 

void main()
{
  char arr[10] = {'a','b','c','d','e','f','g','h','i','j'};
  int res = dichotomy(arr,10,'e');
  printf("%d\n", res);
}

 posted on 2022-04-10 13:50  laremehpe  阅读(45)  评论(0编辑  收藏  举报