因为对二分写法一直模模糊糊,这个函数题琢磨了一下敲了三个不一样的版本。终于理解到为什么说二分没有固定的模板只是一个思路,很多题目都要依题目去思考~浅浅记录一下,若有疑问欢迎私信交流~
目录
函数接口定义:
bool Insert( List L, ElementType X );
其中List
结构定义如下:
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
L
是用户传入的一个线性表,其中ElementType
元素可以通过>、==、<进行比较,并且题目保证传入的数据是递减有序的。函数Insert
要将X
插入Data[]
中合适的位置,以保持结果依然有序(注意:元素从下标0开始存储)。但如果X
已经在Data[]
中了,就不要插入,返回失败的标记false
;如果插入成功,则返回true
。另外,因为Data[]
中最多只能存MAXSIZE
个元素,所以如果插入新元素之前已经满了,也不要插入,而是返回失败的标记false
。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef enum {false, true} bool;
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* 保存线性表中最后一个元素的位置 */
};
List ReadInput(); /* 裁判实现,细节不表。元素从下标0开始存储 */
void PrintList( List L ); /* 裁判实现,细节不表 */
bool Insert( List L, ElementType X );
int main()
{
List L;
ElementType X;
L = ReadInput();
scanf("%d", &X);
if ( Insert( L, X ) == false )
printf("Insertion failed.\n");
PrintList( L );
return 0;
}
/* 你的代码将被嵌在这里 */
代码一:
bool Insert( List L, ElementType X ){
int low=0,high=L->Last,mid,in,i,in1,in2;
if(L->Last+1==MAXSIZE)return false;
while(low<=high){
mid=(low+high)/2;
if(X==L->Data[mid])
return false;
if(X<L->Data[mid])low=mid+1;
else high=mid-1;
}
if(low==mid){//x比mid大
for(i=L->Last;i>=mid;i--){
L->Data[i+1]=L->Data[i];
}
L->Last++;
L->Data[mid]=X;
}
if(high==mid){//x比mid小
for(i=L->Last;i>mid;i--){
L->Data[i+1]=L->Data[i];
}
L->Last++;
L->Data[mid+1]=X;
}
return true;
}
代码二:
bool Insert( List L, ElementType X ){
int low=0,high=L->Last,mid,in,i,in1,in2;
if(L->Last+1==MAXSIZE)return false;
if(X>L->Data[0]){
for(i=L->Last;i>=0;i--){
L->Data[i+1]=L->Data[i];
}
L->Data[0]=X;
L->Last++;
return true;
}
while(low<high){
mid=(low+high+1)/2;
if(X==L->Data[mid])
return false;
if(X<L->Data[mid]12)low=mid;// 向左找答案、找到比他大的第一个数
else high=mid-1;
}
for(i=L->Last;i>high;i--){
L->Data[i+1]=L->Data[i];
}
L->Last++;
L->Data[high+1]=X;
return true;
}
代码三:
bool Insert( List L, ElementType X ){
int low=0,high=L->Last,mid,in,i,in1,in2;
if(L->Last+1==MAXSIZE)return false;
if(X<L->Data[L->Last]){
L->Data[L->Last+1]=X;
L->Last++;
return true;
}
while(low<high){
mid=(low+high)/2;
if(X==L->Data[mid])
return false;
if(X<L->Data[mid])low=mid+1;//向右找答案 、找到比它小的第一个数
else high=mid;
}
for(i=L->Last;i>=high;i--){
L->Data[i+1]=L->Data[i];
}
L->Last++;
L->Data[high]=X;
return true;
}
细节解释待补充》》》