c++实现查找表的顺序查找与折半查找
时间: 2024-02-12 13:09:51 浏览: 87
顺序查找的C++代码实现:
```c++
int sequential_search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
```
折半查找的C++代码实现:
```c++
int binary_search(int arr[], int n, int key) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
```
其中,`arr`是待查找的数组,`n`是数组的长度,`key`是要查找的关键字。顺序查找的时间复杂度为O(n),折半查找的时间复杂度为O(logn)。
相关问题
c++实现查找表的顺序查找和折半查找
顺序查找(线性查找)是一种简单直观的查找方法,适用于线性表的任何情况,但是时间复杂度较高,平均时间复杂度为O(n)。
C++实现顺序查找的代码如下:
```c++
#include<iostream>
using namespace std;
int seqSearch(int arr[], int n, int key){
int i;
for(i = 0; i < n; i++){
if(arr[i] == key)
return i;
}
return -1; //未找到
}
int main(){
int arr[] = {10, 3, 8, 6, 11, 7};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 6;
int pos = seqSearch(arr, n, key);
if(pos == -1)
cout << "未找到" << endl;
else
cout << "找到,位置是:" << pos << endl;
return 0;
}
```
折半查找(二分查找)是一种基于比较的查找算法,适用于已排序的数组,时间复杂度为O(log n)。
C++实现折半查找的代码如下:
```c++
#include<iostream>
using namespace std;
int binarySearch(int arr[], int n, int key){
int low = 0, high = n - 1;
while(low <= high){
int mid = (low + high) / 2;
if(arr[mid] == key)
return mid;
else if(arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; //未找到
}
int main(){
int arr[] = {3, 6, 7, 8, 10, 11};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 6;
int pos = binarySearch(arr, n, key);
if(pos == -1)
cout << "未找到" << endl;
else
cout << "找到,位置是:" << pos << endl;
return 0;
}
```
需要注意的是,折半查找的数组必须是有序的,否则需要先排序后再进行查找。
用C++实现折半查找和顺序查找
折半查找(二分查找):
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int x) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
else if (arr[mid] < x)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, n, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
```
顺序查找:
```c++
#include <iostream>
using namespace std;
int linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x)
return i;
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = linearSearch(arr, n, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
```
阅读全文