查找算法的主函数代码
时间: 2023-08-06 18:15:23 浏览: 42
主函数代码会根据不同的查找算法有所不同,下面给出几种常见查找算法的主函数代码示例:
线性查找:
```c++
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
int index = linearSearch(arr, n, key);
if (index != -1) {
cout << "Found at index " << index;
} else {
cout << "Not found";
}
return 0;
}
```
二分查找:
```c++
int binarySearch(int arr[], int l, int r, int key) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == key) {
return mid;
}
if (arr[mid] > key) {
return binarySearch(arr, l, mid - 1, key);
}
return binarySearch(arr, mid + 1, r, key);
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
int index = binarySearch(arr, 0, n - 1, key);
if (index != -1) {
cout << "Found at index " << index;
} else {
cout << "Not found";
}
return 0;
}
```
哈希查找:
```c++
const int MAX = 10000;
vector<int> hashTable[MAX];
int hashFunction(int key) {
return key % MAX;
}
void insert(int key) {
int index = hashFunction(key);
hashTable[index].push_back(key);
}
bool search(int key) {
int index = hashFunction(key);
for (int i = 0; i < hashTable[index].size(); i++) {
if (hashTable[index][i] == key) {
return true;
}
}
return false;
}
int main() {
insert(10);
insert(20);
insert(30);
insert(40);
insert(50);
int key = 30;
if (search(key)) {
cout << "Found";
} else {
cout << "Not found";
}
return 0;
}
```
以上代码仅供参考,实际使用时需要根据具体情况进行调整。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)