01-complexity 3 binary search, 01-Binary Search
This is a function question. The question provides corresponding interfaces to complete the subfunction. The given function interfaces and struct are defined as follows:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
#define NotFound 0
Typedef int ElementType;
Typedef int Position;
Typedef struct LNode *List;
Struct LNode {
ElementType Data[MAXSIZE];
Position Last; /* Saves the position of the last element in the linear table */
};
List ReadInput(); /* Referee implementation, details are not listed. The element is stored starting from subscript 1 */
Position BinarySearch( List L, ElementType X );
Int main()
{
List L;
ElementType X;
Position P;
L = ReadInput();
Scanf("%d", &X);
P = BinarySearch( L, X );
Printf("%d\n", P);
Return 0;
}
/* Your code will be embedded here */
We can see that we need to perform binary search for a linear table stored in a linked list. The procedure is as follows:
Position BinarySearch( List L, ElementType X )
{
Position mid;
Position low = 1;
Position high = L->Last;
while(low <= high) {
mid = low + (high - low)/2;
if(X < L->Data[mid])
high = mid - 1;
else if (X > L->Data[mid])
low = mid + 1;
else
return mid;
}
return NotFound ;
}
Note that the while LOOP condition must be Left <= Right. Otherwise, when the two indicate the same number, "NotFound" is directly considered if the condition does not enter the loop judgment, resulting in incorrect results.