diff --git a/编程作业/3.二分查找.cpp b/编程作业/3.二分查找.cpp index da21dbc..128a312 100644 --- a/编程作业/3.二分查找.cpp +++ b/编程作业/3.二分查找.cpp @@ -1,5 +1,5 @@ -#include -#include +#include "stdafx.h" +#include #define MAXSIZE 10 #define NotFound 0 @@ -7,39 +7,53 @@ typedef int ElementType; typedef int Position; typedef struct LNode *List; -struct LNode { - ElementType Data[MAXSIZE]; - Position Last; /* ԱһԪصλ */ +struct LNode +{ + ElementType Data[MAXSIZE]; + Position Last;/* 保存线性表中最后一个元素的位置 */ }; -Position BinarySearch( List L, ElementType X ); +List CreatList();//初始化链表 +Position BinarySearch(List L, ElementType X); -int main() +List CreatList() { - List L; - ElementType X; - Position P; - - L->Data = int[]{1,3,5}; - L->Last = 3; - scanf("%d", &X); - P = BinarySearch( L, X ); - printf("%d\n", P); - - return 0; + List L; + L = (List)malloc(sizeof(struct LNode)); + L->Last = NULL; + return L; } -Position BinarySearch( List L, ElementType X ){ +Position BinarySearch(List L, ElementType X) +{ ElementType left = 1; ElementType right = L->Last; - while(leftData[center] < X){ //мֵX Ұ - left = center+1; - }else if(X < L->Data[center]){ //мֵСX - right = center-1; - }else //ҵˣֱӷ + while (left < right) + { + ElementType center = (left + right) / 2; + if (L->Data[center] < X) + left = center + 1; + else if (X < L->Data[center]) + right = center - 1; + else return center; } return NotFound; -} +} + +int main() +{ + List L; + ElementType X; + Position P; + + L = CreatList(); + for (int i = 1; i < 4; i++) + L->Data[i] = 2 * i - 1; + L->Last = 3; + scanf("%d", &X); + P = BinarySearch(L, X); + printf("%d\n", P); + + return 0; +}