1 //查找算法: 2 // 顺序查找 3 // 二分查找(插值查找,斐波那契查找) 4 // 二叉排序树查找 5 // 哈希表查找 6 7 #include <iostream> 8 using namespace std; 9 10 11 /*顺序查找*/ 12 int sequenceSearch(int* arr, int len, int n) 13 { 14 for (int i = 0; i < len; i++) 15 if (arr[i] == n) 16 return i; 17 18 return -1; 19 } 20 21 /*二分查找(非递归版本)*/ 22 int binarySearch(int* arr, int len, int n) 23 { 24 int low = 0, high = n - 1, mid; 25 while (low <= high) 26 { 27 mid = (low + high) >> 1; 28 if (arr[mid] == n) 29 return mid; 30 else if (arr[mid] < n) 31 low = mid + 1; 32 else 33 high = mid - 1; 34 } 35 36 return -1; 37 } 38 39 /*二分查找(递归版本)*/ 40 int binarySearch0(int* arr, int n, int low, int high) 41 { 42 if (low <= high) 43 { 44 int mid = (low + high) >> 1; 45 46 if (arr[mid] == n) 47 return mid; 48 else if (arr[mid] < n) 49 binarySearch0(arr, n, mid + 1, high); 50 else 51 binarySearch0(arr, n, low, mid - 1); 52 } 53 54 return -1; 55 } 56 57 /*插值查找*/ 58 int insertSearch(int* arr, int len, int n) 59 { 60 int low = 0, high = len - 1, mid; 61 while (low <= high) 62 { 63 if (arr[low] == arr[high]) //处理数组中具有相同值的情况 64 if (arr[low] == n) 65 return low; 66 else 67 return -1; 68 69 mid = (int)(1.0*(n - arr[low]) / (arr[high] - arr[low])*(high - low)); //需要转换为double进行计算 70 if (arr[mid] == n) 71 return mid; 72 else if (arr[mid] < n) 73 low = mid + 1; 74 else 75 high = mid - 1; 76 } 77 78 return -1; 79 } 80 81 82 83 int main() 84 { 85 cout << "请输入数组序列和带查找元素 (格式:序列长度n 元素1 元素2 ... 元素n 带查找元素num): " << endl; 86 int n, *parr, num; 87 cin >> n; 88 parr = new int[n]; 89 for (int i = 0; i < n; i++) 90 cin >> parr[i]; 91 cin >> num; 92 93 cout << " 1 顺序查找; 2 二分查找(非递归); 3 二分查找(递归); 4 插值查找; "; 94 cout << "请选择查找模式:"; 95 int selection, index; 96 while (cin >> selection) 97 { 98 switch (selection) 99 { 100 case 1: 101 index = sequenceSearch(parr, n, num); 102 break; 103 case 2: 104 index = binarySearch(parr, n, num); 105 break; 106 case 3: 107 index = binarySearch0(parr, num, 0, n - 1); 108 break; 109 case 4: 110 index = insertSearch(parr, n, num); 111 break; 112 default: 113 break; 114 } 115 116 if (index == -1) 117 cout << "查找失败!" << endl; 118 else 119 cout << "查找成功!位置:" << index + 1 << endl; 120 121 cout << " 请选择查找模式:"; 122 } 123 124 return 0; 125 }