通过线性表实现顺序查找和折半查找c++
时间: 2024-05-06 11:18:32 浏览: 84
顺序查找:
```c++
#include <iostream>
using namespace std;
int sequentialSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10};
int n = sizeof(arr) / sizeof(int);
int target = 6;
int index = sequentialSearch(arr, n, target);
if (index == -1) {
cout << "未找到目标元素" << endl;
} else {
cout << "目标元素在数组中的下标为:" << index << endl;
}
return 0;
}
```
折半查找:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int target) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10};
int n = sizeof(arr) / sizeof(int);
int target = 6;
int index = binarySearch(arr, n, target);
if (index == -1) {
cout << "未找到目标元素" << endl;
} else {
cout << "目标元素在数组中的下标为:" << index << endl;
}
return 0;
}
```
阅读全文