Description
读取10个元素 87 7 60 80 59 34 86 99 21 3,然后建立二叉查找树,中序遍历输出3 7 21 34 59 60 80 86 87 99,针对有序后的元素,存入一个长度为10的数组中,通过折半查找找到21的下标(下标为2),然后输出2
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct BSTNode
{
ElemType key;
struct BSTNode* lchild, * rchild;
}BSTNode,*BiTree;
int Insert(BiTree& tree, ElemType data)
{
if (tree == NULL)
{
tree = (BiTree)malloc(sizeof(BSTNode));
tree->key = data;
tree->lchild = NULL;
tree->rchild = NULL;
return 1;
}
else if (data == tree->key)
{
return 0;
}
else if (data < tree->key)
{
Insert(tree->lchild, data);
}
else if (data > tree->key)
{
Insert(tree->rchild, data);
}
}
void create(BiTree&tree,ElemType data[],int n)
{
int i=0;
while (i<n)
{
Insert(tree,data[i]);//插入二叉排序树
i++;
}
}
int n = 0;
void InOrder(BiTree tree,ElemType i[])
{
if (tree!=NULL)
{
InOrder(tree->lchild,i);
printf("%3d", tree->key);
i[n++] = tree->key;
InOrder(tree->rchild,i);
}
}
int Binary_Search(ElemType i[],int n)
{
int low = 0, high = 9, mid = 0;
while (low<=high)
{
mid = (low + high) / 2;
if (i[mid]==n)
{
return mid;
}
else if (i[mid] < n)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
int main()
{
ElemType data[10];
BiTree tree = NULL;
int x=0;
for (int i = 0; i <10; i++)
{
scanf("%d", &x);
data[i] = x;
}
create(tree, data, 10);
InOrder(tree,data);
printf("\n");
int a;
a=Binary_Search(data,21);
printf("%d", a);
return 0;
}