查找算法簡介及實現
阿新 • • 發佈:2018-03-08
OS selection 選擇 arch cas 二叉排序樹 cout 哈希表 int
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 returnmid; 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 intmid = (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(格式:序列長度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 << "\n1 順序查找; 2 二分查找(非遞歸); 3 二分查找(遞歸); 4 插值查找;\n"; 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 << "\n請選擇查找模式:"; 122 } 123 124 return 0; 125 }
查找算法簡介及實現