查找算法
/* * ===================================================================================== * * Filename: search.h * * Description: template function of search algo * * Version: 1.0 * Created: 2012年04月15日 16时28分42秒 * Revision: none * Compiler: gcc * * Author: Lavey Luo (lavey), [email protected] * Organization: * * ===================================================================================== */ #ifndef __SEARCH_H_ #define __SEARCH_H_ namespace stcpp { /* 顺序查找 */ template<class T> int sequence_search(T a[], int len, T key) { for (int i = 0; i < len; i++ ) { if (a[i] == key) return i; } return -1; } /* 二分查找 */ template<class T> int binary_search(T a[], int len, T key) { int low = 0; int high = len -1; while (low <= high) { int mid = (low + high)/2;/* 折半 */ if (a[mid] < key) { low = mid + 1; } else if (a[mid] > key) { high = mid -1; } else return mid; } return -1; } /* 插值查找 */ template<class T> int interpolation_search(T a[], int len, T key) { int low = 0; int high = len -1; while (low <= high) { int mid = low + (high - low)*(key - a[low])/(a[high] - a[low]); if (a[mid] < key) { low = mid + 1; } else if (a[mid] > key) { high = mid -1; } else return mid; } return -1; } /* 斐波那契查找 */ template<class T> int Fibonacci_Search(T a[], int n, T key) { int i,k=0; int low = 0; /* 定义最低下标为记录首位 */ int high = n -1; /* 定义最高下标为记录末位 */ /* 构建 斐波那契 数组*/ int F[100] = {0}; F[0] = 0; F[1] = 1; for (i=2; i<100; i++) F[i] = F[i-1] + F[i-2]; /* 计算n位于斐波那契数列的位置 */ while(n > F[k]-1) k++; /* 将不满 的数值以最后一个元素的值补全 */ for (i= n - 1; i < F[k]-1; i++) a[i]=a[n -1]; while(low <= high) { int mid=low + F[k-1]-1; if (key < a[mid]) { high = mid - 1; k = k-1; } else if (key > a[mid]) { low = mid + 1; k = k - 2; } else { if (mid <= n - 1) return mid; /* 若相等则说明mid即为查找到的位置 */ else return -1; } } return -1; } } #endif //__SEARCH_H_
测试用例
/* * ===================================================================================== * * Filename: test_search.cpp * * Description: test case of the search.h * * Version: 1.0 * Created: 2012年04月15日 17时41分26秒 * Revision: none * Compiler: gcc * * Author: Lavey Luo (lavey), [email protected] * Organization: * * ===================================================================================== */ #include "search.h" #include <iostream> using std::cout; using std::endl; int test_search(int argc, char** argv) { int a[] = {2, 6, 4, 3, 1, 5}; const unsigned int len = sizeof(a)/sizeof(int); int b[] = {2, 4, 8, 10, 50, 88}; int key = 4; int idx = stcpp::sequence_search(a, len, key); cout << "sequence_search: idx of " << key << " is " << idx << endl;; key = 10; idx = stcpp::binary_search(b, len, key); cout << "binary_search: idx of " << key << " is " << idx << endl; key = 8; idx = stcpp::interpolation_search(b, len, key); cout << "interpolation_search: idx of " << key << " is " << idx << endl; key = 50; idx = stcpp::Fibonacci_Search(b, len, key); cout << "Fibonacci_Search: idx of " << key << " is " << idx << endl; return 0; }