题目要求:
代码实现:
#include<stdio.h>
#define MaxSize 20
#define ElemType int
typedef struct{
ElemType data[MaxSize];
int Length;
}SqList;
SqList L;
void InitList(SqList &L)
{
for(int i=0;i<MaxSize;i++)L.data[i]=0;
L.Length=0;
}
void InsertList(SqList &L,int i,ElemType e)
{
if(i<1||i>(L.Length+1))return;
if(L.Length>=MaxSize)return;
for(int j=L.Length;j>=i;j--)
{
L.data[j]=L.data[j-1];
}
L.data[i-1]=e;
L.Length++;
return;
}
void Exchange(ElemType &a,ElemType &b)
{
ElemType temp;
temp=a;
a=b;
b=temp;
}
void Insert(ElemType *A,int high,int length,ElemType x)
{
int i;
for(i=length-1;i>high;i--)A[i+1]=A[i];
A[i+1]=x;
}
//用最少的时间在表中查找数值为27的元素:
void SearchExchangeInsert(ElemType A[],ElemType x,int length)
{
int low=0,high=length-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]==x)break;
else if(A[mid]<x)low=mid+1;
else if(A[mid]>x)high=mid-1;
}
if(A[mid]==x&&mid!=(length-1))
{
Exchange(A[mid],A[mid+1]);
}
if(low>high)
{
Insert(A,high,length,x);
L.Length++;
}
}
void ShowList(SqList L)
{
printf("输出整个线性表:\n");
for(int i=0;i<L.Length;i++)printf("%d ",L.data[i]);
printf("\n");
}
int main()
{
int e,i=1;
InitList(L);
printf("输入线性表的值:\n");
while(scanf("%d",&e)!=EOF)
{
InsertList(L,i,e);
i++;
}
//用最少的时间在表中查找数值为27的元素:
SearchExchangeInsert(L.data,27,L.Length);
ShowList(L);
return 0;
}