//算法与数据结构实验四-查找 by 022116213-CS
/*1. 在关键字有序序列中采用二分查找法查找关键字为给定值k的元素,输出查找结果。
要求:有序序列和给定值k都从键盘输入。*/
#include "stdio.h"
#include<iostream>
#define MAX 100
using namespace std;
int Binary_Search(const int* array, int n, int key)
{ int low = 1;
int high = n;
int mid;
while (low <= high)
{ if (array[0] < array[1])
{ mid = (low + high) / 2;
if (key < array[mid])
high = mid - 1;
else if (key > array[mid])
low = mid + 1;
else
return mid; }
if (array[0] > array[1])
{ mid = (low + high) / 2;
if (key > array[mid])
high = mid - 1;
else if (key < array[mid]) low = mid + 1;
Else return mid; } } return 0;}
int main()
{ int MAXSIZE;
int key;
cout << "please input the size of the array:";
cin >> MAXSIZE;
int num[MAX];
cout << "please input a sorted sequence:本程序仅可实现有序序列的查找(即递增或递减)";
for (int i = 0; i < MAXSIZE; i++)
{ cin >> num[i]; }
cout << '\n' << "please input the key = ";
cin >> key;
cout << endl;
int key_find = Binary_Search(num, MAXSIZE, key);
if (key_find == 0)
cout << "NOT FOUND!";
else
cout << "The " << key << " is in the " << key_find + 1 << " of the sequence!";
system("pause");
return 0;
}
//算法与数据结构实验四-查找 by 022116213-CS
/*2. 给定关键字序列为{16,5,17,29,11,3,15,20} ,按表中元素的顺序依次插入,建立相应的二叉排序树,给出其中序序列。*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* left;
struct node* right;
}Node;
typedef struct tree {
Node* root;
}Tree;
void create_tree(Tree* tree, int val)
{ Node* node = (Node*)malloc(sizeof(Node)); //定于一个节点,将数放到节点中
node->data = val;
node->left = NULL;
node->right = NULL;
if (tree->root == NULL) {
tree->root = node; //如果根为空,就将这个节点放到根节点}
else { Node* temp = tree->root; //定义指针指向根节点
while (temp != NULL) {
if (val < temp->data) { //如果要放入的值小于根节点
if (temp->left == NULL) { //根节点左孩为空,就直接放入
temp->left = node;
return;}
else {temp = temp->left; //根节点左孩不为空,就指向下一个左孩节点}}
else { if (temp->right == NULL) { //右孩为空,直接放入
temp->right = node;
return;}
else { temp = temp->right; //右孩不为空,指向下一个右孩节点}}}}}
void inorder(Node* node) //中序遍历
{ if (node != NULL) {
inorder(node->left);
printf("中序序列为: %d\n", node->data);
inorder(node->right);}}
int main(int argc, char** argv)
{ int a[8] = { 16,5,17,29,11,3,15,20 };
int i;
for (i = 0; i < 8; i++)
printf("%3d", a[i]);
printf("\n");
Tree tree;
tree.root = NULL;
int len = sizeof(a) / sizeof(int);
for (i = 0; i < len; i++) {create_tree(&tree, a[i]);}
inorder(tree.root);
return 0;}