赞
踩
1、应用随机函数生成100个随机数,数据控制在1-1000之间,并保存到一个数组中。
2、在上一题的基础上,编写代码实现二分查找,例如对用户输入的某个数据,能够进行二分查找,显示找到或没找到,如果找到,请给出查找时的比较次数。
3、在第1题的基础上,编写代码实现二叉排序树的创建,并输出中序遍历该二叉排序树的结果。
4、在第3题的基础上,编写代码实现二叉排序树上的查找,例如对用户输入的某个数据,能够进行查找,显示找到或没找到,如果找到,请给出查找时的比较次数。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
//生成100个随机数存入数组a中
void RAND(int a[])
{
//随机数种子
srand(time(NULL));
for(int i = 0; i < 100; i++)
{
//生成1-1000之间的随机数
a[i] = rand() % 1000 + 1;
}
}
//打印输出数组a中的一百个随机数
void OUTPUT(int a[])
{
for(int i=0;i<100;i++)
{
printf("%5d\t",a[i]);
//控制一行十个数字
if((i + 1 ) % 10 == 0)printf("\n");
}
}
int main()
{
int a[10000];
RAND(a); //生成随机数
OUTPUT(a); //打印输出
return 0;
}
//对随机数进行冒泡排序
void Bubble(int a[]){
for(int i = 0; i < 99; i++){
for(int j = 0; j < 99 - i; j++){
if(a[j] > a[j + 1]){
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
//二分查找 void BinSearch(int a[],int x) { int low = 0,high = 99,z = 0; while(low <= high) { z++; int mid=(low + high) / 2; if(x == a[mid]) { printf("成功找到,数字%d在第%d个位置!",x,mid + 1); printf("\n比较次数:%d次\n", z); return ; } else if(x < a[mid]) { high = mid - 1; } else { low = mid + 1; } } printf("没有找到数字%d",x); return ; }
int main()
{
int a[10000];
RAND(a); //随机生成100个数
Bubble(a); //对前100个数排序
OUTPUT(a); //打印输出前100个数
int x;
printf("输出要查找的数:");
scanf("%d",&x);
BinSearch(a,x); //在数组a的前一百个数中查找元素x
return 0;
}
typedef struct node{
int key;
struct node *lchild,*rchild;
}BSTNode,*BSTree;
void InsertBST(BSTree *bst,int key) { BSTree s; if(*bst==NULL) { s=(BSTree)malloc(sizeof(BSTNode)); s->key=key; s->lchild=s->rchild=NULL; *bst=s; } else if(key<(*bst)->key) { InsertBST(&((*bst)->lchild),key); } else if(key>(*bst)->key) { InsertBST(&((*bst)->rchild),key); } }
void CreateBST(BSTree *bst,int a[])
{
//静态的int变量m
int static m = 0;
int key = a[m++];
*bst = NULL;
while(key!=0)
{
InsertBST(bst,key);
key=a[m++];
}
}
//打印输出排序好的二叉排序数 (中序)
void InOrder(BSTree bst)
{
if(bst!=NULL)
{
InOrder(bst->lchild);
printf("%5d\t",bst->key);
InOrder(bst->rchild);
}
}
int main()
{
int a[10000];
RAND(a); //随机生成100个数
BSTree bst;
CreateBST(&bst,a); //使用数组a中的数创建二叉排序树
InOrder(bst); //打印输出排序好的数
return 0;
}
void SearchBST(BSTree bst, int key) { BSTree q; q = bst; int static i = 0; while(q) { if(q->key == key){ printf("找到了,找了%d次",i); return ; } else { i++; } q->key > key ? q = q->lchild : q = q->rchild; } printf("没有找到,找了%d次",i); return ; }
int main()
{
int a[10000];
RAND(a); //随机生成100个数
BSTree bst;
CreateBST(&bst,a); //使用数组a中的数创建二叉排序树
InOrder(bst); //打印输出排序好的数
int x; printf("\n\n请输入要查找的数:");
scanf("%d",&x);
SearchBST(bst,x); //查找
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。