标签:
查找里面顺比表查找和有序表查找(包括二分查找,插值查找,斐波那契查找)比较简单,直接贴代码,代码里面有详细注释。
1 #include <iostream> 2 using namespace std; 3 4 //顺序表查找(线性查找、静态表查找) 时间复杂度为O(n) 5 int Seq_Search(int *s,int n,int key) 6 { 7 s[0] = key; //设置了一个哨兵,避免了每次比较一次过后都要判断查找位置是否越界 8 int i = n; 9 while (s[i] != key) 10 { 11 --i; 12 } 13 return i; 14 } 15 16 //二分查找(折半查找) 前提条件:记录的关键码必须有序,必须是顺序存储 时间复杂度为O(logn) 17 int Binary_Search(int *s,int n,int key) 18 { 19 int low,mid,high; 20 low = 1; 21 high = n; 22 while (low <= high) 23 { 24 mid = (low + high)/2; 25 if (s[mid] > key) 26 { 27 high = mid - 1; 28 }else if (s[mid] < key) 29 { 30 low = mid + 1; 31 }else 32 return mid; 33 } 34 return 0; 35 } 36 37 //插值查找(对于表长较大,关键字分布比较均匀的查找表来说,插值查找算法的平均性能要比二分查找算法的性能高) 38 int B_Search(int *s,int n,int key) 39 { 40 int low,mid,high; 41 low = 1; 42 high = n; 43 while (low <= high) 44 { 45 mid = low + (high - low)*(key - s[low])/(s[high] - s[low]); 46 if (s[mid] > key) 47 { 48 high = mid - 1; 49 }else if (s[mid] < key) 50 { 51 low = mid + 1; 52 }else 53 return mid; 54 } 55 return 0; 56 } 57 58 //计算斐波那契数列 59 void Fibonacci(int *F) 60 { 61 F[0]=0; 62 F[1]=1; 63 for(int i =2;i<10;i++) 64 { 65 F[i] = F[i-1] + F[i-2]; 66 } 67 } 68 69 //斐波那契查找(时间复杂度是O(logn)) 70 int Fibonacci_Search(int *s,int n,int key,int *F) 71 { 72 int low,high,mid,i,k; 73 low = 1; 74 high = n; 75 k = 0; //k为斐波那契数列的下标 76 while (n > F[k] - 1) //计算n位于斐波那契数列的位置 77 { 78 k++; 79 } 80 for (i = n;i < F[k] -1;i++) //将不满的数值补全 81 { 82 s[i] = s[n]; 83 } 84 //开始查找 85 while (low <= high) 86 { 87 mid = low + F[k] - 1; 88 if (key < s[mid]) 89 { 90 high = mid - 1; 91 k = k - 1; //斐波那契数列下标减一位 92 }else if (key > s[mid]) 93 { 94 low = mid + 1; 95 k = k - 2; //斐波那契数列下标减两位 96 }else 97 { 98 if (mid <= n) 99 { 100 return mid; 101 }else 102 return n; //若mid>n,说明是补全的数值,返回n 103 } 104 } 105 return 0; 106 } 107 108 void main() 109 { 110 int s[] = {0,1,16,24,35,47,59,62,73,88,99}; 111 int n = 11; 112 int m,a; 113 int Fbi[10]; 114 Fibonacci(Fbi); 115 116 cout << "输入顺序表查找要查找的数字: "; 117 cin >> m; 118 a = Seq_Search(s,n,m); 119 cout << "顺序表查找" << m <<"的位置在:"<< a << endl << endl; 120 121 cout << "输入二分查找要查找的数字: "; 122 cin >> m; 123 a = Binary_Search(s,n,m); 124 cout << "二分查找" << m <<"的位置在:"<< a << endl << endl; 125 126 cout << "输入插值查找要查找的数字: "; 127 cin >> m; 128 a = B_Search(s,n,m); 129 cout << "插值查找" << m <<"的位置在:"<< a << endl << endl; 130 131 cout << "输入斐波那契查找要查找的数字: "; 132 cin >> m; 133 a = Fibonacci_Search(s,n,m,Fbi); 134 cout << "斐波那契查找" << m <<"的位置在:"<< a << endl << endl; 135 136 system("pause"); 137 }
运行结果:
标签:
原文地址:http://www.cnblogs.com/tracyhan/p/5506796.html