以下是一些符合 OP 搜索要求的 C 代码:
- 值 < 第一项:返回 0
- 值包含在数组中:返回找到的索引+1
- 值不在数组中但<第一项和<最后一项:返回下一个最大值的索引
- 值 >= 最后一项:返回数组大小
它还演示了 4 种不同类型的二进制搜索:
- 标准二分搜索
- 小于等于二分搜索
- LessThanEqual 或 Last Binary Search
- 下一个最大的二分搜索
(假设没有重复data
)
#include <stdio.h>
int BinarySearch( int key, int data[], const int len )
{
int low = 0;
int high = len-1;
while( high >= low )
{
int mid = low + ((high - low) / 2);
/**/ if (data[mid] < key) low = mid + 1;
else if (data[mid] > key) high = mid - 1;
else return mid ;
}
return -1; // KEY_NOT_FOUND
}
int LessThanEqualBinSearch( int key, int data[], const int len )
{
int min = 0;
int max = len-1;
// var max = data.length - 1; // Javascript, Java conversion
while( min <= max)
{
int mid = min + ((max - min) / 2);
/**/ if (data[mid] < key) min = mid + 1;
else if (data[mid] > key) max = mid - 1;
else /*data[mid] = key)*/return mid ;
}
if( max < 0 )
return 0; // key < data[0]
else
if( min > (len-1))
return -1; // key >= data[len-1] // KEY_NOT_FOUND
else
return (min < max)
? min
: max + 1;
}
int LessThanEqualOrLastBinSearch( int key, int data[], const int len )
{
int min = 0;
int max = len-1;
// var max = data.length - 1; // Javascript, Java conversion
while( min <= max)
{
int mid = min + ((max - min) / 2);
/**/ if (data[mid] < key) min = mid + 1;
else if (data[mid] > key) max = mid - 1;
else /*data[mid] = key)*/return mid ;
}
if( max < 0 )
return 0; // key < data[0]
else
if( min > (len-1))
return len-1; // key >= data[len-1]
else
return (min < max)
? min
: max + 1;
}
int NextLargestBinSearch( int key, int data[], const int len )
{
int low = 0;
int high = len-1;
while( low <= high)
{
// To convert to Javascript:
// var mid = low + ((high - low) / 2) | 0;
int mid = low + ((high - low) / 2);
/**/ if (data[mid] < key) low = mid + 1;
else if (data[mid] > key) high = mid - 1;
else return mid + 1;
}
if( high < 0 )
return 0; // key < data[0]
else
if( low > (len-1))
return len; // key >= data[len-1]
else
return (low < high)
? low + 1
: high + 1;
}
int main()
{
int items[] = { 1, 3, 5, 7, 9, 11 };
int LENGTH = sizeof(items) / sizeof(items[0]);
for( int i = -1; i < 14; ++i )
printf( "[%2d]: == %2d <= %2d <| %d > %d\n", i
, BinarySearch ( i, items, LENGTH )
, LessThanEqualBinSearch ( i, items, LENGTH )
, LessThanEqualOrLastBinSearch( i, items, LENGTH )
, NextLargestBinSearch ( i, items, LENGTH )
);
return 0;
}
输出:
[-1]: == -1 <= 0 <| 0 > 0
[ 0]: == -1 <= 0 <| 0 > 0
[ 1]: == 0 <= 0 <| 0 > 1
[ 2]: == -1 <= 1 <| 1 > 1
[ 3]: == 1 <= 1 <| 1 > 2
[ 4]: == -1 <= 2 <| 2 > 2
[ 5]: == 2 <= 2 <| 2 > 3
[ 6]: == -1 <= 3 <| 3 > 3
[ 7]: == 3 <= 3 <| 3 > 4
[ 8]: == -1 <= 4 <| 4 > 4
[ 9]: == 4 <= 4 <| 4 > 5
[10]: == -1 <= 5 <| 5 > 5
[11]: == 5 <= 5 <| 5 > 6
[12]: == -1 <= -1 <| 5 > 6
[13]: == -1 <= -1 <| 5 > 6
- 该
1st
列是标准的二分查找
- 该
2nd
列是小于二分搜索
- 该
3rd
列是小于或最后二进制搜索
- 该
4th
列是下一个最大的二进制搜索