# include <stdio.h>
# include <stdlib.h>
typedef struct SqList
{
int * elem;
int length;
int listsize;
} sqList;
sqList InitList_Sq ( int Size)
{
sqList L;
L. elem = ( int * ) malloc ( Size * sizeof ( int ) ) ;
if ( ! L. elem)
{
printf ( "初始化失败\n" ) ;
exit ( 0 ) ;
}
L. length = 1 ;
L. listsize = Size;
return L;
}
void binSearch ( sqList L, int k)
{
int low= 1 ;
int high= L. length;
while ( low<= high)
{
int mid= ( low+ high) / 2 ;
if ( k== L. elem[ mid] )
{
printf ( "元素 %d 的位置为: %d\n" , k, mid) ;
break ;
}
else if ( k< L. elem[ mid] )
high= mid- 1 ;
else
low= mid+ 1 ;
}
if ( low> high)
{
printf ( "不存在你所找的元素,请重新输入:\n" ) ;
}
}
void binSearch1 ( sqList L, int k)
{
int low= 1 ;
int high= L. length;
while ( low<= high)
{
int mid= ( low+ high) / 2 ;
if ( k== L. elem[ mid] )
{
printf ( "元素 %d 的位置为: %d\n" , k, mid) ;
break ;
}
else if ( k> L. elem[ mid] )
high= mid- 1 ;
else
low= mid+ 1 ;
}
if ( low> high)
{
printf ( "不存在你所找的元素,请重新输入:\n" ) ;
}
}
int main ( )
{
printf ( "您想创建升序表还是降序表?(升序请输入“1” / 降序请输入“2”)\n" ) ;
int p;
scanf ( "%d" , & p) ;
printf ( "您想在顺序表中输入几个元素?\n" ) ;
int size;
scanf ( "%d" , & size) ;
sqList L1= InitList_Sq ( size) ;
for ( int i= 1 ; i<= L1. listsize; i++ )
{
printf ( "请输入第 %d 个元素: " , i) ;
scanf ( "%d" , & L1. elem[ i] ) ;
L1. length++ ;
}
printf ( "输出顺序表:\n" ) ;
for ( int i= 1 ; i<= L1. listsize; i++ )
{
printf ( "%d\t" , L1. elem[ i] ) ;
}
if ( p == 1 )
{
printf ( "\n" ) ;
while ( 1 )
{
printf ( "你想查找的元素是?\n" ) ;
int x;
scanf ( "%d" , & x) ;
binSearch ( L1, x) ;
}
}
if ( p == 2 )
{
printf ( "\n" ) ;
while ( 1 )
{
printf ( "你想查找的元素是?\n" ) ;
int x;
scanf ( "%d" , & x) ;
binSearch1 ( L1, x) ;
}
}
return 0 ;
}