int binarySearch(int arr[], int l, int r, int x) { while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == x) { return mid; } if (arr[mid] < x) { l = mid + 1; } else { r = mid - 1; } } return -1; }3.分别确定3条路径,满足100%语句覆盖、完全分支覆盖、完全谓词覆盖,并推导出相应路径的路径谓词表达式
时间: 2023-12-20 15:03:50 浏览: 104
1. 100%语句覆盖路径:l=0, r=4, x=2 -> mid=2 -> arr[mid]==x -> return 2
路径谓词表达式:无
2. 完全分支覆盖路径:l=0, r=4, x=2 -> mid=2 -> arr[mid]==x -> return 2
路径谓词表达式:l<=r && (arr[mid]==x || arr[mid]<x)
3. 完全谓词覆盖路径:l=0, r=4, x=2 -> mid=2 -> arr[mid]==x -> return 2
路径谓词表达式:l<=r && (arr[mid]==x || (arr[mid]>=x && r=mid-1) || (arr[mid]<=x && l=mid+1))
相关问题
写出二分法查找的代码(arr为按升序排列的数组,key为待查找的元素,n为数组长度,返回值为key所在的元素的下标,未找到返回-1)(搜索算法)备注:int binary_search(int *arr, int key, int n)
好的,这是二分查找的代码实现:
```
int binary_search(int *arr, int key, int n) {
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
```
二分法查找是一种高效的查找算法,它的时间复杂度为O(logn)。在每次比较的时候,都可以将查找区间缩小一半,直到找到或者区间为空。
改变以下代码变量名使代码重复率降低的同时保留代码原理与功能,#include <stdio.h> #include <stdlib.h> int BinSearch(int R[], int n, int k) { int low=0,high=n-1,mid,count=0; while(low<=high) { mid=(low+high)/2; printf("第%d次查找:在[ %d ,%d]中找到元素R[%d]:%d\n ",++count,low,high,mid,R[mid]); if(R[mid]==k) return mid; if(R[mid]>k) high=mid-1; else low=mid+1; } return -1; } int main() { int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int k, loc; printf("Please input your number: \n"); scanf("%d", &k); loc=BinSearch(a, 10, k); if(loc == -1) printf("not find!"); return 0; }
#include <stdio.h>
#include <stdlib.h>
int binarySearch(int arr[], int size, int key) {
int low = 0, high = size - 1, mid, count = 0;
while(low <= high) {
mid = (low + high) / 2;
printf("The %d time searching: Find element arr[%d]: %d in [%d, %d]\n", ++count, mid, arr[mid], low, high);
if(arr[mid] == key)
return mid;
if(arr[mid] > key)
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int key, index;
printf("Please enter a number: \n");
scanf("%d", &key);
index = binarySearch(arr, 10, key);
if(index == -1)
printf("Not found!\n");
return 0;
}
阅读全文