检索的
Question one
# include "ArrayIo.h"
# define N 10000
int seqsearch ( int a[ ] , int n, int key)
{
int i = 0 ;
a[ n] = key;
while ( a[ i] != key) i++ ;
if ( i == n) return - 1 ;
else return 1 ;
}
int main ( )
{
int a[ N] , n, x, pos;
n= readData ( a, N, "data1.txt" ) ;
printf ( "请输入要查找的整数:" ) ;
scanf ( "%d" , & x) ;
pos= seqsearch ( a, n, x) ;
if ( pos== - 1 )
printf ( "查找失败" ) ;
else
printf ( "a[%d]=%d\n" , pos, x) ;
}
Question two
# include "slnklist.h"
# define N 100
linklist seqsearch ( linklist head, int key)
{
linklist p = head;
while ( p && p-> info != key) p = p-> next;
if ( p) return p;
else return NULL ;
}
int main ( )
{
linklist head, pos;
int x;
head= creatLink ( "data1.txt" , N) ;
print ( head) ;
printf ( "请输入要查找的整数:" ) ;
scanf ( "%d" , & x) ;
pos= seqsearch ( head, x) ;
if ( pos== NULL )
printf ( "查找失败!\n" ) ;
else
printf ( "查找成功!%d\n" , pos-> info) ;
delList ( head) ;
}
Question three
# include "ArrayIo.h"
# define N 10000
int binSearch ( int a[ ] , int n, int key)
{
int l = 0 , r = n - 1 ;
while ( l <= r)
{
int mid = l + r >> 1 ;
if ( a[ mid] == key) return mid;
else if ( a[ mid] < key) l = mid + 1 ;
else r = mid - 1 ;
}
return - 1 ;
}
int main ( )
{
int a[ N] , n, x, pos;
n= readData ( a, N, "data2.txt" ) ;
printf ( "请输入要查找的整数:" ) ;
scanf ( "%d" , & x) ;
pos= binSearch ( a, n, x) ;
if ( pos== - 1 )
printf ( "查找失败" ) ;
else
printf ( "a[%d]=%d\n" , pos, x) ;
}
Question four
# include "ArrayIo.h"
# define N 10000
int binSearch ( int a[ ] , int low, int high, int key)
{
if ( low > high) return - 1 ;
int mid = low + high >> 1 ;
if ( a[ mid] == key) return mid;
else if ( a[ mid] < key) return binSearch ( a, mid + 1 , high, key) ;
else return binSearch ( a, low, mid - 1 , key) ;
}
int main ( )
{
int a[ N] , n, x, pos;
n= readData ( a, N, "data2.txt" ) ;
printf ( "请输入要查找的整数:" ) ;
scanf ( "%d" , & x) ;
pos= binSearch ( a, 0 , n- 1 , x) ;
if ( pos== - 1 )
printf ( "查找失败" ) ;
else
printf ( "a[%d]=%d\n" , pos, x) ;
}
Question five
# include "Arrayio.h"
# include "bstree.h"
# define N 100
bstree creatBstree ( int a[ ] , int n)
{
bstree t= NULL , parent, p, q;
int i, flag;
for ( i= 0 ; i< n; i++ )
{
parent= NULL ;
p= t;
flag= 0 ;
while ( p)
{
if ( p-> key> a[ i] )
{
parent= p;
p= p-> lchild;
}
else if ( p-> key< a[ i] )
{
parent= p;
p= p-> rchild;
}
else
{
flag= 1 ;
break ;
}
}
if ( flag== 0 )
{
q= ( bstree) malloc ( sizeof ( bsnode) ) ;
q-> key= a[ i] ;
q-> lchild= q-> rchild= NULL ;
if ( ! t) t= q;
else
if ( q-> key < parent-> key)
else
parent-> rchild= q;
}
}
return t;
}
int main ( )
{
int n, a[ N] ;
bstree p, t;
n= readData ( a, N, "data1.txt" ) ;
output ( a, n) ;
t= creatBstree ( a, n) ;
printf ( "中序遍历:\n" ) ;
inorder ( t) ;
return 0 ;
}