大话数据结构
Unit7 查找
查找算法举例
代码
#include<iostream>
using namespace std;
//顺序查找
//a为数组,n为数组长度,key为关键字
int Search(int* a, int n, int key) {
int i;
for (i = 0;i <= n;i++) {
if (a[i] == key) {
return i;
}
}
return 0;
}
//书序查找优化
//有哨兵的顺序查找
int Search2(int* a, int n, int key) {
int i;
a[0] = key; //设a[0]为关键字值,称之为哨兵
i = n; //循环从数组尾部开始
while (a[i] != key) {
i--;
}
return i; //返回0则说明查找失败
}
//折半查找
//要求数组为由小到大的有序数组
//n为数组长度加1
int BinarySearch(int* a, int n, int key) {
int low, high, mid;
low = 1;
high = n;
while (low <= high) {
mid = (low + high) / 2;
if (key < a[mid]) {
high = mid - 1;
}
else if(key>a[mid]){
low = mid + 1;
}
else {
return mid;
}
}
return 0;
}
//插值查找
int BinarySearch2(int* a, int n, int key) {
int low, high, mid;
low = 1;
high = n;
while (low <= high) {
mid = low + (high - low)*(key-a[low])/(a[high]-a[low]);
if (key < a[mid]) {
high = mid - 1;
}
else if (key > a[mid]) {
low = mid + 1;
}
else {
return mid;
}
}
return 0;
}
//斐波那契数列
int F(int n) {
if (n == 1 || n == 2) {
return 1;
}
else if (n == 0) {
return 0;
}
else {
return (F(n - 1) + F(n - 2));
}
}
//斐波那契查找
int FebonacciSearch(int* a, int n, int key) {
int low, high, mid, i, k;
low = 1;
high = n;
k = 0;
while (n > F(k) - 1) {
k++;
}
for (i = n;i < F(k) - 1;i++){
a[i] = a[n];
}
while (low <= high) {
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) {
return mid;
}
else {
return n;
}
}
}
return 0;
}
int main() {
int a[6] = { 1,2,3,4,5,6 };
cout<< Search(a, 5, 2)<<endl;
int b[7] = {0,1,2,3,4,5,6 };
cout << Search2(b, 6, 2) << endl;
cout << BinarySearch(b, 6, 5)<<endl;
cout << BinarySearch2(b, 6, 4)<<endl;
cout << FebonacciSearch(b, 6, 1) << endl;
return 0;
}