不确定为什么 return 不是元素的索引?

Not Sure why this doesn't return the index of the element?

不确定为什么 return 没有搜索到的元素的索引。输入是排序后的数组、它的大小和要查找的元素。

int binarySearch(int a[], int size, int key){
  int mid = (size)/2;
  if(a[mid] == key){
    return mid;
  }else if(size ==1 || size ==0){
      return -1;
  }

  if(key<a[mid]){
    return binarySearch(a, mid, key);
  }else if (key > a[mid]){
    return binarySearch(a+(mid), size-mid, key);
  }
}

如果 key > a[mid],你必须 return mid + binarySearch(a+(mid), size-mid, key),因为 binarySearch 只会看到数组的后半部分,因此 return 是第二部分的索引一半。