本帖最后由 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;
}
|