查找算法大集合

来源:互联网 发布:数控机床与编程教程pdf 编辑:程序博客网 时间:2024/06/06 03:15

1.顺序查找

int sequnceSearch(const int* array, const int length, const int findValue) {if (NULL == array || 0 >= length) {return -1;}for (int i = 0; i < length; ++i) {if (findValue == array[i]) {return i;}}return -1;}

2.折半查找

int binarySearch(const int* array, const int length, const int findValue) {if (NULL == array || 0 >= length) {return -1;}int left = 0, right = length - 1;int middle = (left + right) / 2;while (left <= right) {middle = (left + right) / 2;if (findValue > array[middle]) {left = middle + 1;} else if (findValue < array[middle]) {right = middle - 1;} else {return middle;}}return -1;}

3.插值查找

int insertSearch(const int* array, const int length, const int findValue) {if (NULL == array || 0 >= length) {return -1;}int left = 0, right = length - 1, middle = 0;while (left < right) {middle = left+ (findValue - array[left]) / (array[right] - array[left])* (right - left);//避免分母为0的情况if (findValue > array[middle]) {left = middle + 1;} else if (findValue < array[middle]) {right = middle - 1;} else {return middle;}}return findValue == array[left] ? left : -1;}

4.Fibonacci查找

int fibonacci(int* array, const int length, const int findValue) {if (NULL == array || 0 >= length) {return -1;}int k = 0, fibLength = length;int* fib = new int[fibLength];fibonacci(fib, fibLength);while (length > fib[k] - 1) {++k;}int left = 0, right = length - 1;int middle = 0;for (int i = length; i < fibLength; ++i) {array[i] = fib[right] - 1;}while (left <= right) {middle = left + fib[k] - 1;if (findValue > array[middle]) {k = k - 1;left = middle + 1;} else if (findValue < array[middle]) {k = k - 2;right = middle - 1;} else {return middle;}}return -1;}

测试代码

#include<iostream>using namespace std;void createSearchArray(int* array, const int length) {if (0 >= length) {return;}cout << "请输入" << length << "个元素:" << endl;for (int i = 0; i < length; ++i) {cout << i << '\t';cin >> array[i];}}void printSearchArray(const int* array, const int length) {if (NULL == array || 0 >= length) {return;}for (int i = 0; i < length - 1; ++i) {cout << array[i] << '\t';}cout << array[length - 1] << endl;}int main() {int length = 0;cout << "输入数据的长度:" << endl;while (cin >> length) {int* x = new int[length];int findValue = 0;createSearchArray(x, length);printSearchArray(x, length);for (int i = 0; i < length; ++i) {findValue = x[i];cout << "findValue:" << findValue << endl;cout << "顺序查找的结果:" << sequnceSearch(x, length, findValue) << endl;cout << "折半查找的结果:" << binarySearch(x, length, findValue) << endl;cout << "插值查找的结果:" << insertSearch(x, length, findValue) << endl;cout << "Fibonacci查找的结果:" << insertSearch(x, length, findValue)<< endl;}cout << endl;cout << "输入数据的长度:" << endl;}return 0;}




0 0
原创粉丝点击