请你用c++实现二分查找的非递归算法,要求待查找/待排序的记录用数组存储,且记录个数不小于100000个,记录的初始状态自定义;要对每个算法进行计时;
时间: 2024-03-02 13:53:40 浏览: 55
好的,我可以帮你实现二分查找的非递归算法。以下是代码实现:
```c++
#include <iostream>
#include <ctime>
using namespace std;
int binarySearch(int arr[], int low, int high, int target)
{
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(int argc, char** argv)
{
const int n = 100000;
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = rand() % n; // 随机生成100000个数
}
sort(arr, arr + n); // 对数组进行排序
clock_t start, end;
int target = 99999;
start = clock();
int index = binarySearch(arr, 0, n - 1, target);
end = clock();
if (index != -1)
cout << "The element is found at index " << index << endl;
else
cout << "The element is not found." << endl;
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << fixed << time_taken << setprecision(5);
cout << " sec " << endl;
return 0;
}
```
这个程序会在数组中查找一个目标值,并返回该值的索引。程序首先生成一个包含100000个数字的随机数组,然后对其进行排序。接下来,程序测量使用二分查找算法查找目标值的时间,并输出结果。
阅读全文