|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
红色的地方编译有错误,不知道哪里有问题
#include <stdio.h>
#define MAXSIZE 5
typedef int ElementType;
typedef int Position;
typedef struct LNode *List;
struct LNode{
ElementType data[MAXSIZE];
Position Last;/*保存数组Data[]中最后一个元素的位置*/
};
Position BinarySearch(List, ElementType);
int main()
{
List L;
L = (List)malloc(sizeof(struct LNode));
L->data = {12, 31, 55, 89, 101};
L->Last = sizeof(L->data);
ElementType X = 31;
Position ret;
ret = BinarySearch(L, X);
printf("%d is %d", X, ret);
return 0;
}
Position BinarySearch(List L, ElementType X)
{
Position Left, Right, Mid;
Left = 1;
Right = L->Last;
while(Left <= Right)
{
Mid = (Left + Right) / 2;
if(L->data [Mid] > X)
Right = Mid - 1;
else if(L->data [Mid] < X)
Left = Mid + 1;
else
return Mid;
}
}
本帖最后由 superbe 于 2019-12-13 22:33 编辑
少头文件了吧#include <malloc.h>
BinarySearch的逻辑有点问题,修改的代码:
- #include <stdio.h>
- #include <malloc.h>
- #define MAXSIZE 5
- typedef int ElementType;
- typedef int Position;
- typedef struct LNode *List;
- struct LNode {
- ElementType data[MAXSIZE];
- Position Last;
- };
- Position BinarySearch(List, ElementType);
- int main()
- {
- List L;
- L = (List)malloc(sizeof(struct LNode));
- //L->data = { 12, 31, 55, 89, 101 };
- L->data[0] = 12;
- L->data[1] = 31;
- L->data[2] = 55;
- L->data[3] = 89;
- L->data[4] = 101;
- L->Last = sizeof(L->data) / sizeof(ElementType);
- ElementType X = 31;
- Position ret;
- ret = BinarySearch(L, X);
- (ret > 0) ? printf("%d is %d\n", X, ret) : printf("Not found\n");
- return 0;
- }
- Position BinarySearch(List L, ElementType X)
- {
- Position Left, Right, Mid;
- Left = 1;
- Right = L->Last;
- while (Left <= Right)
- {
- Mid = (Left + Right) / 2;
- if (L->data[Mid - 1] == X)
- return Mid;
- if (L->data[Mid - 1] > X)
- Right = Mid - 1;
- else if (L->data[Mid - 1] < X)
- Left = Mid + 1;
- }
- return -1;
- }
复制代码
|
|