查找一:C++静态查找
1 #include<iostream> 2 using namespace std; 3 #define MAXSIZE 100 4 5 int Seq_Search(int *a, int n, int key) 6 { 7 int i; 8 for(i=0; i<n;i++) 9 { 10 if(a[i]==key) 11 return i; 12 } 13 return 0; 14 } 15 16 //折半查找 17 int In_Search(int *a, int n, int key) 18 { 19 int low, high, mid; 20 low = 0; 21 high = n-1; 22 while(low<high) 23 { 24 mid = (low+high)/2; 25 if(a[mid]>key) 26 { 27 high--; 28 } 29 else if(a[mid]<key) 30 { 31 low++; 32 } 33 else 34 return mid; 35 } 36 return 0; 37 } 38 39 //插值查找 40 int Insert_Search(int *a, int n, int key) 41 { 42 int low, high, mid; 43 low = 0; 44 high = n-1; 45 while(low<high) 46 { 47 //插值 48 mid = low + (high-low)*(key-a[low])/(a[high]-a[low]); 49 if(a[mid]>key) 50 { 51 high--; 52 } 53 else if(a[mid]<key) 54 { 55 low++; 56 } 57 else 58 return mid; 59 } 60 return 0; 61 } 62 63 //斐波那契数列 64 void Fibonacci(int *F) 65 { 66 F[0] = 0; 67 F[1] = 1; 68 for(int i=2;i<MAXSIZE;i++) 69 { 70 F[i] = F[i-1] + F[i-2]; 71 } 72 } 73 74 //斐波那契查找 75 int Fibonacci_Search(int *a, int n, int key) 76 { 77 int low = 0; 78 int high = n-1; 79 int mid; 80 int F[MAXSIZE]; 81 Fibonacci(F); 82 int k =0; 83 while(n>F[k]-1) 84 k++; 85 int *temp = new int[F[k]-1]; 86 memcpy(temp,a,n*sizeof(int)); 87 for(int i=n;i<F[k]-1;i++) 88 temp[i] = a[n-1]; 89 90 while(low<high) 91 { 92 mid = low + F[k-1] - 1; 93 if(key<temp[mid]) 94 { 95 high = mid-11; 96 k = k-1; 97 } 98 else if(key>temp[mid]) 99 { 100 low = mid+1; 101 k = k-2; 102 } 103 else 104 { 105 if(mid<n) 106 return mid; 107 else 108 return n-1; 109 } 110 } 111 delete[] temp; 112 return -1; 113 } 114 115 int main() 116 { 117 int a[MAXSIZE]; 118 for(int i=0;i<MAXSIZE;i++) 119 a[i] = i+1; 120 cout << Seq_Search(a,MAXSIZE,45)<<endl; 121 cout << In_Search(a,MAXSIZE,45)<<endl; 122 cout << Insert_Search(a,MAXSIZE,45)<<endl; 123 124 int arr[] = {0,16,24,35,47,59,62,73,88,99}; 125 int key=73; 126 int index=Fibonacci_Search(arr,sizeof(arr)/sizeof(int),key); 127 cout<<key<<" is located at: "<<index; 128 129 system("PAUSE"); 130 return 0; 131 }