用C++实现一些查找算法。
测试代码
#include <iostream>
#include <algorithm>
using namespace std;
//顺序查找
int sselect(int a[], int len, int k) {
for (int i = 0; i < len; i++) {
if (k == a[i])
return i;
}
return -1;
}
//折半查找(递归)
int binary_select(int a[], int low, int high, int k) {
if (low > high) {
return -1;
} else {
int mid = (low + high) / 2;
if (k < a[mid]) {
return binary_select(a, low, mid - 1, k);
} else if (k > a[mid]) {
return binary_select(a, mid + 1, high, k);
} else
return mid;
}
}
//折半查找(非递归)
int binary_select2(int a[], int len, int k) {
int low = 0, high = len - 1, mid;
while (low <=high) {
mid = (low + high) / 2;
if (a[mid] == k)
return mid;
else if (k < a[mid])
high = mid - 1;
else
low = mid + 1;
}
return -1;
}
//二叉树结点的定义
typedef struct BiNode {
int data;
struct BiNode *lchild, *rchild;
} BiNode, *BiTree;
//二叉排序树的插入
int insertBitree(BiTree &T, int x) {
if (T = NULL) {
T = (BiTree) malloc(sizeof(BiNode));
T->data = x;
T->lchild = NULL;
T->rchild = NULL;
return 1;
} else if (x == T->data)
return -1;
else if (x < T->data)
return insertBitree(T->lchild, x);
else
return insertBitree(T->rchild, x);
}
//二叉排序树的建立
void creatBitree(BiTree &T, int a[], int len) {
T = NULL;
int i = 0;
while (i < len) {
insertBitree(T, a[i]);
i++;
}
}
//二叉排序树的查找
int selectBitree(BiTree T, int x) {
if (!T)
return -1;
else {
if (x = T->data)
return 1;
else if (x < T->data)
return selectBitree(T->lchild, x);
else
return selectBitree(T->rchild, x);
}
}
//2 4 6 13 19 22 56 77 81
int main() {
int n;
cin >> n;
int *nums = new int[n];
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
// if (binary_select(nums, 0, n - 1, 22) != -1) {
// cout << "该元素在数组中第" << binary_select(nums, 0, n - 1, 22) + 1 << "位";
// } else {
// cout << "未找到该元素";
// }
// if (sselect(nums, n, 77)) {
// cout << "该元素在数组中第" << sselect(nums, n, 77) + 1 << "位";
// } else
// cout << "未找到该元素";
if (binary_select2(nums, n, 19)) {
cout << "该元素在数组中第" << binary_select2(nums, n, 19) + 1 << "位";
} else
cout << "未找到该元素";
return 0;
}