二分法
1.二分法程序
2.测试
3.断言
4.自动测试
5.计时
Assert:指导程序代码的开发,也可以用来判断程序的正确性。使用assert断言表示相信某个逻辑表达式为真,语句assert(n>=0)在n为0或更大时什么都不做,但在n为负时会报告某种错误。
程序:
int n;
int x[4096] = {0};
// return position if t in sorted x[0..n-1] or -1 if t is not present
int binarysearch(int t)
{
int lower, upper, mid;
lower = 0;
upper = n - 1;
while(lower <= upper)
{
mid =(lower + upper) / 2;
if(x[mid] < t)
{
lower = mid + 1;
}
else if(x[mid] == t)
{
assert(0 <= mid && mid < n && x[mid] == t);
return mid;
}
else // x[m] > t
upper = mid - 1;
}
assert((upper < 0 || x[upper] < t) && (upper + 1 >= n || x[upper+1] > t));
return -1;
}
// 检查数组数据是否顺序排列
int sorted()
{
for(int i = 0; i < n - 1; i++)
{
if(x[i] > x[i + 1])
return 0;
}
return 1;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
while(scanf("%d", &n) != EOF)
{
clock_t timeStart = clock();
for(int i = 0; i <= n; i++)
{
x[i] = 10 * i;
}
printf("\n");
if(sorted())
{
for(int i = 0; i < n; i++)
{
assert(binarysearch(10*i) == i);
assert(binarysearch(10*i - 5) == -1);
}
assert(binarysearch(10*n - 5) == -1);
assert(binarysearch(10*n) == -1);
}
clock_t timeEnd = clock();
printf("timeStart = %ld, timeEnd = %ld, timeEnd - timeStart = %ld \n", timeStart, timeEnd, timeEnd-timeStart);
}
return a.exec();
}